Node.js > Call function with button

39 views
Skip to first unread message

Junior Domingos

unread,
Sep 3, 2016, 12:05:41 AM9/3/16
to nodejs
 Does anyone know in Node.js to call an external file function by clicking a button in html?

Aria Stewart

unread,
Sep 3, 2016, 12:11:35 AM9/3/16
to nodejs


On Saturday, September 3, 2016 at 12:05:41 AM UTC-4, Junior Domingos wrote:
 Does anyone know in Node.js to call an external file function by clicking a button in html?

Maybe. It depends on what you mean by 'external file function'.

If it's a commonjs module that is the external file function, then you can require it into an http server.

server.js:

var http = require('http');
var fs = require('fs');
var externalFunction = require('./externalfunction.js');
http.createServer(req, res) { 
   if (req.method == 'post') {
      externalFunction();
      res.end('ok');
   } else {
      res.setHeader('content-type: text/html');
      fs.createReadStream('button.html').pipe(res);
   }
}).listen(8080);

And some HTML:

button.html

<form action="." method=post>
   <button>Do the thing</button>
</form>


If you run that server script, it will listen on port 8080. http://localhost:8080/ should show the button, and if you click it, the server should call the function.
Reply all
Reply to author
Forward
0 new messages