X

nodeJS : A Server side JavaScript

Node.Js is a software system designed for writing scalable web server applications. Programming is done in JavaScript, and are using event-driven, asynchronous I/O to minimize overhead and maximize scalability.

Node.js mainly uses Google’s V8 JavaScript engine and several other built-in libraries. We have already heard about client side Javascript, but not server side JavaScript.

Google has developed ultra fast Javascript interpreter in C++ which is used in Chrome Browser. As it is available for download, we can use it in our applications as well and is not restricted for a browser.

The following code is written for a simple server which responds with “Hello World” for every request.

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8000/');

To run the server, you need to write the code in to a server.js and execute it with the node program:

% node server.js
Server running at http://127.0.0.1:8000/

The following is an example of a simple TCP server which listens on port 8000 and echoes whatever you send it:

var net = require('net');
net.createServer(function (stream) {
stream.write('hello\r\n');
stream.pipe(stream);
}).listen(8000);

One of the main goal of node.js is to allow to write scalable network programs. The normal languages like PHP, .net, Java seeds new thread on each connection which utilizes almost 2MB of memory in RAM. For a 4GB of RAM, server can allocate 2000 concurrent users. If the number of client increases we have to increase the hardware which results in spending more money.

Node.js was selected by InfoWorld for the Technology of the Year Award in 2012.

Node solves this issue by changing the way how connection is made to the server. It will trigger an event to the node’s core engine process instead of spawning new thread for each connection. As there is no locks allowed in node, so will never be a deadlock. Node allocates the resources on demand, and there is no pre-allocation of large resources for each connection.

This post was last modified on February 14, 2012 11:36 am

Admin: