In this tutorial, we will learn how to serve HTML pages to clients using Node.js. Let's get started!

Step 1: Create an HTML File

Go to your project and create a new HTML file. Name it home.html. Open the file and add the HTML5 boilerplate code, along with some text inside the body:


<!DOCTYPE html>
<html lang=`en`>
<head>
<meta charset=`UTF-8`>
<meta http-equiv=`X-UA-Compatible` content=`IE=edge`>
<meta name=`viewport` content=`width=device-width, initial-scale=1.0`>
<title>Home</title>
</head>
<body>
<h1>Home Page</h1>
</body>
</html>

Step 2: Create a Server in Node.js

Next, open the index.js file and require the http and fs packages. Write the following code:


var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req,res)
{
    res.writeHead(200,{'Content-Type':'text/html'});
    var readStream = fs.createReadStream(__dirname + '/index.html');
    readStream.pipe(res);
});
server.listen(3000);
console.log(`server is running on localhost:3000`);

Step 3: Run the Server

Now, let's run the server. Go to the command prompt and execute the following command:


node index.js

The server is now running on localhost:3000. Open a web browser and navigate to localhost:3000. You should see the HTML page you created earlier.

That's it! You have successfully served an HTML page using Node.js. This is a basic example, but it demonstrates the power of Node.js in serving web content.