HTTP Module in Node Js


In this tutorial, we are going to learn about the http module in node js. We will learn about importing the module and also see how to create a server using it.


What is an HTTP module in Node Js?

Node.js comes with a built-in module of http whose role is to transfer data by creating an HTTP server which listens to ports and sends back a response. In order to use the module in nodejs, we will use the require() function.

var http = require('http')

Recommended Books


Let’s use the HTTP module to create an HTTP server which listens to ports and sends back a response. We will use the createServer() method to create an HTTP server:

var http = require('http');

//creates a server:
http.createServer(function (req, res) {
  res.write('Hello World!'); //write Hello World as a response
  res.end(); //Ending the response
}).listen(3000); //the server listens at 3000 port

In the above example, we have first imported the http module by using the require() function. Since it is a built in module in node js so we don’t have to install it through the node package manager.

Creating the Server in Node Js

Next we create a server using the createServer() method and further designate two arguments to the function known as req and res, which will the receive the request and response from the server. At last, we will add a listen() method which will keep on listening the requests at a certain port. In our case, the port is 3000. 

You can even add a console message so that when you run the code, you can always know when the server has started listening

//creates a server:
http.createServer(function (req, res) {  
res.write('Hello World!'); //write Hello World as a response  
res.end(); //Ending the response
}).listen(3000); //the server listens at 3000 port

console.log("Server has started listening at port 3000")

Create a file known as server.js and paste the above code in it. Use the terminal or command prompt to run the server.js file in node by using the following command.

http module in node js

Above, you can see that the server.js file is running and the server has started listening at 3000. If you go to your browser and find the 3000 port through the local host http://localhost:3000, you will see the following output:

http module 2