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:
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:
- Create a file named
app.jsand add the code to it. - Create an
index.htmlfile with the desired content. - Run the command
node app.jsin 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