Home > Software engineering >  How do I use Node functions and variables from HTML while using a server?
How do I use Node functions and variables from HTML while using a server?

Time:10-23

I'm trying to build a few programs that execute Node.js functions from HTML (e.g you press a button and some code using Node.js runs).

Here is the code I'm using to display the HTML

var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "."   q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    } 
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

CodePudding user response:

(Too long for a comment.)

First you must decide whether pressing a button shall

  1. lead to a complete new HTML page that contains the results of the Node.js code execution or
  2. update only parts of your existing HTML page.

In the first case, sending back static HTML pages (as your code does) will not be sufficient, you would need a template engine.

In the second case, you need client-side Javascript code to fetch JSON data (say) from your server and update the DOM of your HTML page.

  • Related