Tuesday, January 3, 2012

Create server in NodeJs - Server side Javascript

Nodejs is a simple javascript [Server side] which creates an http server with a specified port. Yes, it is creating a http server by using its library. Now suppose you have IIS or apache in your machine, running on a port 80. Now, if we run bellow code , it will create a server with a different port number[suppose : 8088]. Now , if you run the  url : http://localhost/ and http://localhost:8088/ ,two different server will be accessed. 

var http = require("http");   //import http
http.createServer(function(request, response) { //create server in node js
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write(“<h1>Hi to nodejs</h1>”);  // return for the request.
  response.end();
}).listen(8088); //port for the server is specified
 
A small code for creating server dynamically. We can see- request and response as input with create Server. These will contain the request and response object.  I bit strange structure, right. Here createServer function takes a function as an input which takes request and response as it’s input.  If any doubt ,please ask me.  
But, how or where we will run this code? A bit work needs to be done.
Download NodeJs from http://nodejs.org/ . Run it in in the development machine[it supports Windows,Linux and MAC; I used windows]. You will get the Nodejs folder in the installation location. It contains - node_modules, node.exe and npm.cmd. To execute the code above , you have to use node.exe . Go to command prompt -> nodejs folder. This is where you will use your code. Create a folder called MyServer.  Save your code in it [Suppose : server.js]. That’s it. You are ready to go.
Command to execute the code-

>node  “C:\Program Files\nodejs\MyServer\server.js”

Now , open any browser and put http://localhost:8088/  in address bar.  You will see a big ->                   Hi to nodejs. You can design any page structure using HTML in the place of “<h1>Hi to nodejs</h1>”.
That’s it for now. Enjoy J
Post a Comment