Create an HTTP Server in NodeJS

In our previous node example we simply printed “hello world” on our console using node command. In this post we will see how we can create an http server using nodejs and send a response from the server to the browser to print a text.

Step 1: Let us create a server.js file on our system.

Step 2: To create an http server need to import a node module ‘http’. We don’t need to install it separately as it comes bundled with the nodejs installation. We will use require() method to import ‘http’ module and save it inside a variable named ‘http’.

var http=require('http');

Step 3: Next we need to call the createServer() method of the http module and save the instance of that server in a variable named server. The createServer() takes as a parameter an anonymous function which accepts two parameters – request and response. The ‘request’ variable will have the data related to the requests which this server receives from the browser when its running and ‘response’ is responsible for providing the result back to the browser.

var server=http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end('Hello World');
});

server.listen(3000,function(){
console.log("server running on localhost:3000");
});

When we return data back to the browser we need to use writeHead() method which accepts two values – first one is 200 which means that data has been successfully received from the server and second value is the content-type i.e. what type of data is being send from the server. It can be plain text, html, json, image, etc.

end() method of the response is used to actually set or write the data back to the browser. In our case we are sending ‘hello world’ text.

Step 4: We need to manually set the port number on which this server will run. Our server will run on port 3000.

Here is the complete code for server.js

var http=require('http');

var server=http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end('Hello World');
});

server.listen(3000,function(){
console.log("server running on localhost:3000");
});

Step 5: Open the terminal or command prompt and go the directory where you have saved the server.js file and run the server file using node command.

node server.js

You will see something like this on your screen.

Screen Shot 2015-06-02 at 11.42.54 pm

Step 6: Goto your browser and open localhost:3000. “Hello World” should be displayed on it (which by the way is coming from the server).

Screen Shot 2015-06-02 at 11.44.36 pm

Congrats you have created your first http node server. In our next post we will see how we can run the server.js file on the actual server and not on our local machine.

Related Posts