0

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?

goken son
  • 11
  • 1
  • Sure you are sending 2 tags to browser and calling a function that is not defined in browser, but it Node.js ?? It is quite complicated to communicate between client and server - there is no direct client/server relation. Last time used pupeteer for something similar - Node.js to fill and run PDF.js viewer. Process PDF there and send data using exposeFunction back to Node.js - standard path would be load special page and submit data for example. Or you can use pupeteer too (using indirect WebSocket communication). Check my changes here https://github.com/eltomjan/pdf.js.git – Jan Dec 07 '20 at 14:33

1 Answers1

0

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 -

<script src="server.js"></script>

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 -

const express = require('express');
const app = express();

app.set('view engine', 'ejs');

app.get('/book', function(req, res) {
  res.render('index');
});

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.

app.post('/book', function(req, res) {
  // req.body will have submitted form data.
  // You can then do modification.
  // You need to use body-parser.
});
Viral Patel
  • 1,104
  • 4
  • 7