Create my first Node.js HTTP server

I am a web developer and till now I used the JavaScript only for front end client-side development on the web browsers. But JavaScript is not limited only on the client-side.

After I heard about Node.js I know that JavaScript can also be used as a server-side programming language. So I decided to make my hand dirty in programming on Node.js. So I just started learning it.

The very first thing I did on Node.js is creating an HTTP server. So here in this article, I am going to tell you how I create my first Node.js HTTP server with the necessary JavaScript code.

The Node.js HTTP Module

I came to know about the Node HTTP module. This module is already in-built in Node.js. It allows to create server and transfer data over HTTP.

To use this module, we just need to include the HTTP module using the in-built require() method of Node.js. Below is how to include the HTTP module in Node.js:

var http = require('http');

After including the module, we can use it in our application.

Create a server on Node.js using HTTP module

Create a JavaScript file server.js. Now put the code below in that file to create an HTTP server:

var http = require('http');

//create a server object:
http.createServer(function (req, res) {
  res.write('My first node HTTP server'); //response to the client
  res.end(); //end of the response
}).listen(1000); //the server object listens on port 1000

So what we did in our code?

Here we have first created a server object using the createServer() method of http module. Inside this method, we have to write a response text and then end it. We pass 1000 in the listen method so that the http.createServer() method be executed when user access on port 1000.

So we are ready to run our code. Now you can initiate the server.js file:

D:\nodefolder>node server.js

Now you can access the server on the browser just by visiting http://localhost:1000/ on a browser.

So we did it. Now you can also create your first Node.js HTTP server by following this article.

Leave a Reply

Your email address will not be published. Required fields are marked *