NodeJS Series Part 4: Creating a Port Listener

Here I will describe NodeJS which is Part 4 of NodeJS series. The purpose of this article is about creating a server, listening to it through a port number and then sending output to the browser.

Hello Wizards.

First of all, I apologize for not publishing this article as I promised,i had illness.Even Wizards get sick!

The purpose of this article is all about creating a server, listening to it through a port number and then sending output to the browser.

So let's start immediately!

We shall write a small script that creates a server and listens to this object.

  1. var http = require("http");  
  2. http.createServer(function (request, response) {  
  3.    response.writeHead(200, { "Content-Type""text/plain" });  
  4.    response.write("Listening to localhost:8888");  
  5.    response.end();  
  6. }).listen(8888);  
Let's take a breath and talk about what this script does in detail, shall we?
  1. var http = require("http");  

The first line of the code tells us it will use a http object and implement it. You can interpret this statement as importing a namespace to the project and referencing it.

  1. http.createServer(function (request, response) {  

This code does create a server object with the 2 parameters request and response. Clearly you know HTTP works depending on Requests and Responses. The same thing here.

  1. response.writeHead(200, { "Content-Type""text/plain" });  
  2. response.write("Listening to localhost:8888");  
  3. response.end();  

As said earlier, when you request this server object, it will send the 200 code (Success) and Content-Type Headers to the server object. Afterwards,we will write specifying as if it listens to the server via a port number and later we end the response object so that we cand send buffered output to the response and stop executing the page and thus end the request.

  1. }).listen(8888);  

Now that's the last thing we should be doing, listening to the port number.

Do you realize that we only used a port number here? That means we shall use “localhost” for testing purposes.

Can't we use an IP with port number? Yes, you can!

If you have changed the code as in the following:

  1. }).listen(8888, '127.0.0.1'););  

Then it would still work.

Now since we cleared up a few things here, we can test the server now!

Store the sample JavaScript file in a close location and then run the Node.js command prompt as in the following:

node5

Press Enter.

You will see a server object created and now it listens to the localhost:8888, right? :)So, open your favorite web browser and navigate to this server!

output
As long as the Nodejs command prompt runs, you can access the server object and do some stuff!

Remember one thing: Creating a server object is the first step in creating a Rest service with Node.js.

And I plan on writing an article about that in the following series.

I hope this article was useful for you.