Node.js Technology and How to Use It
Join the DZone community and get the full member experience.
Join For Freenowadays 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
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.
Opinions expressed by DZone contributors are their own.
Trending
-
Auditing Tools for Kubernetes
-
Extending Java APIs: Add Missing Features Without the Hassle
-
Observability Architecture: Financial Payments Introduction
-
Competing Consumers With Spring Boot and Hazelcast
Comments