How to Create HTTP Web Server in Node.js

Node.js Tutorial – We shall learn to create HTTP Web Server in Node.js using http.createServer() method of HTTP Built-in Module.

Create HTTP Web Server in Node.js

Node.js provides built-in module, HTTP, which is stable and is compatible with NPM ecosystem.

Following is a step by step tutorial, to Create HTTP Web Server in Node.js :

Step 1 : Include HTTP Module

Create a .js file with name httpWebServer.js and open in a text editor.

Include the Built-in Node.js module, HTTP, using require function as shown below.

Step 2 : Create Server

Create a server using the method createServer() to listen at port numbered 9000.

Step 3 : Prepare response

We shall prepare a response with HTTP header and a message.

Step 4 : Run the Web Server

Run the httpWebServer.js file (from previous step) to create and make the server listen at port 9000.

The server will be up and running.

Step 5 : Test the Web Server

Open a browser and hit the url, “http://127.0.0.1:9000/”, to trigger a request to our Web Server.

Create HTTP Web Server in Node.js

 

Voila! We have created a HTTP Web Server that listens on port numbered 9000 and responds with HTML formatted text message ”Node.js says hello!” for any request.

This may not be a full fledged Web Server that you expect for your projects, but this is for sure a stepping in our journey of building HTTP Web Server.

Conclusion :

In this Node.js Tutorial – Create HTTP Web Server in Node.js, we have used http.createServer() method of HTTP Built-in Node.js module to create HTTP Web Server that responds to the requests made at a port.