Menu Close

How to run HTML file using Node.js?

Run HTML file using Node.js

To run HTML file using Node.js, we call readFile to read the file and http module.

For instance, we write below code and save index.js.

Note: Keep index.html file in same path.

const http = require("http");
const fs = require("fs");

const PORT = 8080;

fs.readFile("./index.html", (err, html) => {
  if (err) throw err;

  http
    .createServer((request, response) => {
      response.writeHeader(200, { "Content-Type": "text/html" });
      response.write(html);
      response.end();
    })
    .listen(PORT);
}); 

To call readFile to read index.html.

And then we serve it by call http.createServer to start a web server with a callback that calls write with the html file content to serve that.

 

Then run node index.js then you will get data in http://localhost:8080/

Posted in HTML, NodeJs

You can also read...