Categories
JavaScript Answers

How to run HTML file using Node.js?

Spread the love

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

For instance, we write

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 serv it by call http.createServer to start a web server with a callback that calls write with the html file content to serve that.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *