How to serve a HTML page in Node.js



Previous article showed you how to create a basic server. Now lets look around the way to serve a html page using Node.js. First create a index.html file in your project folder.

<html>
<head>
  <title>Home Page</title>
</head>
<body>
  <h1>My first Template</h1>
  <p>Hypertext Markup Language is the standard markup language for creating web pages and web applications. With Cascading Style Sheets and JavaScript, it forms a triad of cornerstone technologies for the World Wide Web</p>
</body>
</html>

Now lets see how to serve this page. Take a look at the code below.

var http=require('http');
var fs = require('fs');
var server = http.createServer(function(req,res){
  console.log('request made :'+req.url);
  res.writeHead(200,{'Content-Type': 'text/html'});
  var read=fs.createReadStream(__dirname + '/index.html','utf8');
  read.pipe(res);

});

server.listen(3000,'127.0.0.1');
console.log('Hey you are now listening to port 3000');

In the above code we have changed the content type into html to serve it as a html page. Without sending plain text to the browser we have created a html page and have sent it to the browser. Run the command line and then the browser to see the output. 

Comments