I need the Nodejs-fileserver for saving some text but I want to do this with a website written in html. How can I do something like this? Here is an example but there only comes the failure: 'book() isn't defined'.
const http = require('http');
const fs = require('fs');
http.createServer( function (req, res) {
res.writeHead(200,{'Content-Type': 'text/html'})
res.write('<meta charset="utf-8">');
res.write('<button onclick="book(this)">Buchen</button>');
res.end();
}).listen(8080);
function book(sender)
fs.appendFile('test.csv',sender, function (err) {
if (err) {throw err};
console.log("Schreiben erfolgreich");
});
}
When I connect the nodejs file with the script tag, can I handle the code of the html file?
<script src="server.js"></script>
How can I execute the nodejs book() function with the html button?
You might need to read this answer first. Due to JavaScript, a single language on both client and server side, it might cause some confusion when you start with Node.js.
But, that doesn't mean you can't perform operations onClick from HTML. You surely can do it using Ajax or form submit. I would also suggest you to use Express.js framework.
Also, you can't include the file like this -
Because it's not a client-side normal JavaScript file even though it has
.js
extension. It is a server-side file.Talking about example, you can do something like this -
When you visit /book route, it'll open an index view which might have a form to submit. Then you can write code within /post POST url to do further modification.