Wednesday 2 May 2012

Create a simple HTTP server with Node.js

With so much of the hype of node.js and the server side javascript i decided to give it a go, the post is not really as complicated as the title may look like, node.js allows you to get real taste of the core protocols which we tend to ignore while using frameworks, though there are some good application frameworks for building node applications like Express and Geddy but in the initial stage one should learn the way it really works out IMO... so without fuether ado lets get down to writing the http server, i assume that you have success fully installed node.js HERE is a useful link.

After the installation you can check the version of the node by typing

node -v

into the terminal window, i'm using fedora 15 (lovelock). Ok now create a file and name it server.js and put the following code inside it
var http = require("http");

http.createServer(function(request, response) {

  response.writeHead(200, {"Content-Type": "text/plain"});

  response.write("Hello Node");

  response.end();

}).listen(8088);


in-order to listen to port 80 you would require the root privileges so i'm not getting into that.

 The first line of code is used to include pre-build module of http more on node modules in the later posts...

the rest is very obvious, cd to the directory where server.js is residing and type

[fedora@localhost HelloNode]$ node server.js


 now  just redirect your browser to

 http://localhost:8088
 
and it will greet you with the

message "Hello node"...

Congratulations you have made yourself a http server

P.S i took help from this guide