Wednesday, February 13, 2013

Simple Http Server in NodeJS

Hello Guys , here is my post on "Simple Http Server" in NodeJS

In the last tutorial , we studied how to make log on console !

In this tutorial , we will study how to make "Hello World" response to the client
who has requested to our server

With NodeJS , it is very easy to make simple http servers with a very small amount of code

NodeJS has provided a tool called "Node Package manager" or shortly called npm. Module are reusable pieces of code so that

we can import/ include it in our project by using the following function
   
    require('MODULE_NAME');

This function returns a object of that module

With npm we can install , update or remove modules from our project .

So lets begin with making our Simple http server

for this we need the http module

if you are using Mac or Linux , use the following command

sudo npm install http -g

if you are using windows , it takes some steps ,
1) create a file called package.json


2) code to you project directory and run the following command
  
npm install

your module will get install

Now comes the coding

1)First take a object of 'http' using 'require'
2)make an object called 'server' by using 'createServer' method of 'http' module
3)make a request response function that set the 'content-type' and sends some data as 'reponse'
4)listen on some port number
Your code will look like this


Thats it !! You are done !!!

run the code by using following command




Now open your browser and type the "http://localhost:3000"
you will get the following result

You can also do the same thing from any other computer in your network ,
Get the ip-address of the pc where this node server is up . suppose its "10.49.14.106"
Then go the browser on that pc ,  do the same thing , You will get the following result


Hurray !! You made a Server !!