HTML5 Zone is brought to you in partnership with:

Natalia represents IT outsourcing company SMISS Ltd. Natalia's main focus in SMISS Blog is organization and management of outsourcing process, general questions about software and application development, IT and company news. Natalia has posted 5 posts at DZone. You can read more from them at their website. View Full User Profile

Node.js Technology and How to Use It

04.30.2014
| 3524 views |
  • submit to reddit

Nowadays Node.js is a quickly developing technology and has already became very popular. Let's have a look what this technology can be used for, its advantages and disadvantages and why we need it.

What is Node.js?

Node.js is a programming platform that allows you to execute mostly server-side code that is identical in syntax to browser JavaScript. But in browser we are limited in using all language possibilities as we have to provide security for user. In such case usually all activity is aimed to DOM-manipulation and also asynchronous page info loading. Node.js opens up new perspectives, still having its “browser” nature.  

Node.js characteristics

Node.js is based on V8 engine developed for Chrome browser by Google corporation, as a framework for javascript execution. Library libuv is used in both Windows and POSIX-based systems like Linux, Mac OS X and Unix for abstraction of functionality of files, network, etc. The same as in browser, server-side javascript is the same single-threaded process of events with non-blocking input/output. But now there is a possibility to log program work into file, that puts Node.js on par with other technology that allow to develop executable applications. It allows to achieve high capacity, but not productivity. The point is that the parts of code are put in turn, but if there is an event that takes more time to execute, you may have a feeling that Node.js program is stuck. Also it is well-known fact that Node.js is limited to 1 GiB memory, that is prewritten in the V8 engine. (It is so-called historical burden from the browser, where the limitation was implemented. It was made in order to overloaded by javascript applications and also applications with wrong code that can overload allocated memory won't take all computers RAM together with browser).  

Main advantages and usage of Node.js

Node.js main advantage is that it doesn't have any flaws that usually appear when we work with streams - creation of new data structures providing stream work, blocking memory, etc. For example, in Apache web-server for every connection the new stream is created with initial data of 2 MiB.

One of the advantages of Node.js is the fact that for application development using this technology you need to know only JavaScript.

Taking into account the specific features of Node.js, it is mainly used for development of next types of programs:

- Programs executing one task in one launch, so-called scripts. 

- Executable applications, such as different types of servers. But in such application a developer should apply to some rules in order to provide high capacity. All actions should be smaller in order to keep high level of capacity, and also we should check that the application isn't overloaded by memory consumption.  

Node.js usage example: message server based on socket.io

message server set up

Now we will have a look at the example of Node.js application realization using library socket.io, that will execute functions of message server.

First of all, you should remember that you should use Node.js in development with a modular approach, so that code is not only readable, but also easy to maintain, extensible and would be able to be used for various purposes, if necessary (example of such module you will see further is listing chatServer.js). Then the code to run our server may look like this:

var chatServer = require('./lib/chatServer').ChatServer(443);
chatServer.start();

where: 

require('./lib/chatServer') returns link to module (module is js file with the name, in our case,  chatServer, that provides external methods). It also reveals one method for external usage – ChatServer(443) constructor with the port parameter that server should “listen to”.

- further chatServer is an object of our server that has methods like start( ), which launches our server.

Listing file chatServer.js:

module.exports = {
	ChatServer: function(port) { return new ChatServer(port);}
}
function ChatServer(port) {
	//creating http server for the webSocketServer
	this.httpServer = require('http').createServer(function(request, response) {
    	console.error('Received request for ' + request.url);
    	response.writeHead(200);
    	response.end('Server is on!');
	});
	this.io = require('socket.io').listen(this.httpServer, {
    	'log level': 0,
    	'log colors': false
	});
	this.app = require('./app').Application();
	this.port = port;
	this.logger = require('log4js').getLogger("all");

}

ChatServer.prototype.start = function() {
	var logger = this.logger;

	var port = this.port;
	this.httpServer.listen(this.port, function() {
    	    	console.info('Server is listening on port '+port);
    	});

	var app = this.app;
	var io = this.io;

	this.io.sockets.on('connection', function (socket) {
    	socket.userId = socket.handshake.query['user'];
    	app.controller(io.sockets.clients(),{
        	command: "userLoggedIn",
        	data: {
            	username: socket.userId
        	}
    	}, socket);

     	socket.on('message', function (data) {
        	console.log(data);
        	app.controller(io.sockets.clients(),data, this);
    	});
    	socket.on('disconnect', function (data) {
        	console.info('User logged out with id: ' + this.userId);
    	});
	});


	return true;
};

ChatServer.prototype.stop = function() {
	// closing connections and shutting down server
}

In the file above you may find a kind of class (as javascript doesn't have class as it is). But we will stick to this term “class”. Class has a constructor and two methods to start server and stop it.

Also, usual http server is created in constructor, it is transferred to Socket.io server in order to manage WebSocket connections. 

What I'd like to stop at is message controller which is also created as separate class. All incoming messages are transfered to the method controller(message) :

Application.prototype.controller = function(connections, message, sender) {
	message.data.date = new Date().getTime();
	// Collector
	var collectedParameters = {
    	OrderSystemClient: this.OrderSystemClient,
    	connections: connections,
    	message: message,
    	sender: sender
	}
	// Default responsible
	var responsible = {
    	resposibleForCommand: 'Default',
    	handle: function(params) {
        	console.warn("Unsupported command: '" + params.message.command + "'");
    	}
	}
	//Find responsible
	for(var i in this.chainOfCommandHandlers) {
    	if(message.command==this.chainOfCommandHandlers[i].resposibleForCommand) {
        	responsible = this.chainOfCommandHandlers[i];
    	}
	}
	// Handle request with found responsible
	responsible.handle(collectedParameters);
}

Every message has a field command, and based on this field an action that should be executed is chosen in the method above. Please note that two templates are used: functional objects and chain of responsibility.ChainOfCommandHandlers - is exactly a chain of responsibility. Such realization allows to divide code into small pieces, and dynamic changes of chain of responsibility may make the action reply to the message faster. Readability and flexibility of the program also increases. 

Conclusion

We used class and module approaches together with programming patterns in the development of example above. As you can see, such code is readable, easy to modify and portable.

From one side, in order to write applications using Node.js you don't need to have high level qualification.  But, from my experience, if you don't use such approaches your application will turn into the long code sheet, that is difficult to read and to support, and  it is easier to rewrite it if you need to modify it than to try understanding the original code. 

Development process using Node.js has its advantages and disadvantages as any other technology. Such qualities altogether allow us to solve certain tasks. So to answer the question, "Whether to use Node.js or not?" you need to evaluate whether Node.js conforms to the requirements of the project, as well as compare it with others analogs, using such factors as technical specifications or technology development prospects.

In conclusion I'd like to say that neither technology is holy Grail, vice-versa, every technology  is supposed to solve some specific list of tasks. 

Published at DZone with permission of its author, Natalia Pankova.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)