NodeJs http module is a built-in module. It comes by default when you install NodeJs.

Node Js http module is used to create server on a port. Port Number is of user choice.

There are three steps involved in using http module :

1.) Include the Module:

Any module in Node Js can be included using require method. http module can be included as below:

var http = require(‘http’);

2.) Create the Server

Server can be created on a port using createServer() method.

var http = require('http');
http.createServer(function(request,response){


}).listen(8089);

3.) Write the logic inside the createServer() function.

var http = require('http');
http.createServer(function(request,response){

   response.write('This is http module demo program');
   response.end();

}).listen(8089);

How to run this demo http module program??

1.Save this as httpdemo.js

2. Go to command prompt where httpdemo.js is saved and type node httpdemo.js

3. Go to browser and hit http://localhost:8089/ and you will get the below result in the browser :

This is http module demo program

How to Add HTTP Header in Response??

For adding header use writeHead() method on response object.
e.g.

Suppose ‘Content-Type’ is to be added in the header.

var http = require('http');
http.createServer(function(request,response){
   response.writeHead(200,{'Content-Type': 'text/html'});
   response.write('This is http module demo program');
   response.end();

}).listen(8089);

Leave a Reply