/

How to Serve an HTML Page using Node.js

How to Serve an HTML Page using Node.js

Learn how to easily serve an HTML page using Node.js without any dependencies.

Recently, I came across a requirement to serve an HTML page from a Node.js server. After some research, I found the simplest code that gets the job done. Below is the code snippet:

1
2
3
4
5
6
7
8
9
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-type': 'text/html' });
fs.createReadStream('index.html').pipe(res);
});

server.listen(process.env.PORT || 3000);

As you can see, this code doesn’t require any additional dependencies.

To implement this code, follow these steps:

  1. Create a file named app.js and add the code to it.
  2. Create an index.html file with the desired content.
  3. Run the command node app.js in your terminal or command prompt.

Please note that the above code serves only the index.html page and doesn’t provide support for serving static assets.

Tags: Node.js, HTML, server, HTTP