Category Archives: NODE.JS


What is Callback in Node.JS?

Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they support callbacks.

For example, a function to read a file may start reading file and return the control to execution environment immediately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.


What is Stdout flush in NodeJS?

For example

sys.stdout.write(“hello I am Writing something”);

Stdout flush is used for checking writable stream is “write” successful or not.

“sys.stdout.flush()” gives result true if flush was successful and false if kernel buffer is full and it can’t write yet.


Node.js Framework Comparison

Express.js, Koa.js and Hapi.js are the most popular Node.js application frameworks of today and all of them have obvious similarities. Node.js frameworks enable web developers to create a server with few lines of code and creating REST API has become very simple.


Express.js is undoubtedly the most popular Node.js application framework in contemporary web development world. Popular frameworks like Sails.js are built based on Express.js and it was described as a “fast and small server side Javascript web development framework built on node.js and V8 Javascript engine” in a web development journal. The current version of Express.js is 4.x

Express.js gained prominence as a web application framework for building single page and multi-page web apps. The finest attraction of Express.js is that many of its features are available as plug-ins and it is the backend component of MEAN stack(MongoDB ExpressJS AngularJS NodeJS). Douglas Christopher and Wilson are the developers of Express.js and it is a cross platform operating system.

Express.js can be downloaded using NPM and the command ‘npm install-g express’ in the node CLI for installing Express.JS. The quickest and easiest way to create express application architecture is to install express generator. Setting for Express applications can be obtained using the app.set and app.get methods. Application level, router level, third party and cookie middleware are available in Express.js web framework. Biggest contribution of Express.js is that it gave backend functionality that allows developers to build software with script on the server side. They can develop server side applications with Node.js and publish those ap plications as websites using Express.js.

var express = require(‘express’);
var app = express();

app.get(‘/’, function (req, res) {
res.send(‘Hello World!’);

var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;

console.log(‘Example app listening at http://%s:%s’, host, port);

” The app starts a server and listens on port 3000 for connection. It will respond with “Hello World!” for requests to the root URL (/) or route. ”


Koa.js is termed as the next generation web application framework for the one and only Node.js. Objective of Koa development team was to build a smaller, expressive and robust foundation for web applications. Koa application is an object containing a wide array of middleware generator functions and they are composed in a stack like manner. Koa is almost similar to other middleware systems like Ruby’s Rack, Connect and so on. Content negotiation, cache freshness and proxy support are the spectacular features provided by Koa.js. It allows performing actions downstream, filter and then manipulating the response upstream. Methods common to all HTTP servers can be integrated directly into Koa’s small 550 SLOC database. This includes numerous functionalities like content negotiation, nominalization of node inconsistencies and redirection. Koa.js is not bundled with any middleware and it is supported in all versions of iojs without any flags. Web developers all over the world were super excited after the initial release of Koa.js and the curious fact is that Koa.js was developed by the same team who developed Express.js.

Koa is known for heavily leveraging Javascript generators provided by Harmony and Javascript generators refer to an experimental technology.

A simple hello world program in Koa.js is illustrated below.

1: var koi = require (‘koi’);
2: var app = koi ();
4: app. use (function *() {
5: this. Body = ‘Hello World';
6 :});
8: app. listen (3000);

We should be running node 0.11.9 or higher along with harmony flag for Javascript generator support. Koa is an innovative and pragmatic Node.js framework which can be used for building complex web applications.


Being known as a rich framework for building web applications, Hapi.js enables developers to focus on writing reusable application logic. Hapi is currently used by global corporate giants including PayPal, Walmart, Yahoo as well as Mozilla. As a web application framework, Hapi.js enables granular control over incoming requests. Hapi plug-ins can be broken into small applications with separate business logic very easily and servers should provide only configuration. In tech world, Hapi is being recognized as a battle tested framework for Node.js made by Walmart.

Hapi features huge amount of well maintained official plug-ins including OAuth. Configuration over convention approach of Hapi.js has become a hot topic of discussion among web development experts who are more inclined to convention-overconfiguration approach. Official version is that configuration based approach made the implementation of requirement theme very easy. Hapi.js will be an ideal tool for web developers who are keen on high availability, easy testing as well as easy theming.

var Hapi = require(‘hapi’);

var server = new Hapi.Server();
server.connection({ port: 3000 });

method: ‘GET’,
path: ‘/’,
handler: function (request, reply) {
reply(‘Hello, world!’);
server.start(function () {
console.log(‘Server running at:’,;

Save the above as server.js and start the server with the command node server.js. Now, if you visit http://localhost:3000 in your browser, you’ll see the text Hello, world!.


Node.js is a single thread application. Does it support multi-process or platforms and utilize all the processor resources?

Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources.

It is believed that more performance and scalability can be achieved by doing async processing on a single thread under typical web loads than the typical thread based implementation. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port


Best Node.js Performance Tips You Can Adopt

All of us know about the rapid adoption of JavaScript in the previous decade and major reason behind the popularity of JavaScript is the influence of Node.js. Node.js is the software platform used for building fast, robust and scalable network applications. It is mainly based on Google’s V8 Javascript search engine or the Chrome browser runtime. Node.js features an event­driven architecture and an I/O API that optimizes application scalability. One of the most important feature of Node.js is that it contains built­in library that acts as a web server and there is no need for web server such as IIS or Apache Web Server.

It is perceived that Javascript is the most used language on GitHub. Ryan Dahl, the creator of Node.js says , “ after over twenty years of stateless­web based on the stateless request-response paradigm, we finally have web applications with real time two way connections”. Need for adapting to the new technology of Node.js is actively discussed in global tech community including these prominent performance tips.

Going Asynchronous
Node.js is single threaded and there are lots of synchronous components that can lock up the entire application. It is practical to use an external library that has a blocking call and use of asynchronous API is the best possible solution. While choosing third party modules, it is to be ensured that external library does not revert to synchronous calls.

Keeping Code Small
Keeping code small and light is one of the most talked about node.js performance tips we can adopt. In the contemporary age of critical mobile application performance, it is important to keep Node.js code as compact as possible. Node.js is made compact for reducing latency as well as speeding things up.

Developers of node.js face the following questions during development stage

  • “Do we really need this module”?
  • “Why are we using this framework”?
  • “Is it worth the overhead”?

“Is there another way to optimize application performance by concatenating multiple JS files into one?”­ This statement can be explained with the help of an example. If a web app has five Javascript files, the browser will make five separate HTTP requests to fetch them and the best approach would definitely be to concatenate those five files into a single one.

DO NOT use Node.js for static assets:
Don’t use Nodejs to serve static assets like client JS, CSS, fonts or images. This is not good because Node doesn’t do this efficiently. Say we ask for a reasonably large image file and we’re serving it from a Express mount-point, this works when we’re developing it locally, because it’s just us using it. No load really. Use NGINX or CDN to deliver such static assets to reduce the load on your application server.

Don’t Store Too Much in Sessions
By default in a typical Express web app, the session data is stored in memory. Storing too much data in the session, it adds significant load to the server. Instead storing their id in the session will reduce the load on an app server rather than storing the entire object. So, either you can switch to different storages like MongoDB or Redis to store session data or go session­free with EXPRESS JS.

Here is an example of initializing the session.
app.use(express.session({ secret: “mysterious triangle” }));

Run in Parallel
Generally if we want to run multiple functions at a time, we need to wait for the previous function to execute. So to reduce latency we can go for parallel operations to run. To execute these calls in parallel, we can use Step.JS (A simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless). This accepts any number of functions as arguments and runs as the callback to the next step.

Use Client Side Rendering When Possible
DO NOT render (or send) templates from Node JS side. Do it on client side using templating engines like Handlebar. Infact better do it using CDN so it can be cached. For dynamic content (like data), deliver it via JSON. So after the initial page load, the only data sent to the client is the dynamic JSON, which is maximally efficient. This approach dramatically reduces the CPU, IO, and load on Node.js.

Major companies using NODEJS and Why?
Global business giants like PayPal, Yahoo, EBay, Netflix, The Mail Online, and Walmart are betting big on Node.js. Tech giants are passionate of embracing power of Node.js for embedded devices and robotics. Node.js dominates the real time web application arena by using push technology that gives them a distinctive edge over server side web applications.

Chat applications are classic examples of lightweight, real time and data intensive applications of Node.js. It has been debated that two way communication and communication has been there since many years in the form of Java applets or Flash.

The promising technology of Node.js plays a pivotal role in the technology realm of any large business organization. What would be the possible reason? It is only because Node.js allows web developers to build one code base using one language. Performance, scalability, and short web development cycles help Node.js to find a place in the big league of technology innovations in 21st century.

“Node.js powers our web applications and has allowed our teams to move much faster in bringing their designs to life”­ PayPal


Which tools could be used to debug Node.js applications?

Many times when a complex situation arises. A good debugging tool will make our lives easy. Here some of the tools that you may consider to “npm install”

  1. node­inspector
  2. Joyent
  3. Node Webkit Agent
  4. NodeJS Plugin for WebStrom
  5. Cloud9 IDE (has built in debugger for Node)



How to pass command line arguments to Node.js?

Three ways to pass the command line arguments to node.js

  • Using process.argv – process.argv is an array containing the command line arguments. The first element will be ‘node’, the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

// print process.argv
process.argv.forEach(function (val, index,
array) {
console.log(index + ‘: ‘ + val);
This will Genearate,
$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four

  • Using yargs module – It is a light-weight option parsing with an argv hash.
  • Using minimist module – It is a module which parse argument options.