Category Archives: NODE.JS


Handy Utilities for Node.js

Handy Utilities for Node.js

Node.js is a tool used in different ways in a variety of workflows and for a variety of purposes such as Front-end, back-end, APIs, robotics, APIs, and much more.

Node.js has been one of the best tools to build small, modular tools to make developer’s lives easier.

In this article, we have collected a list of different modules that a developer can install globally on their system to help improve their development workflow.


Firstly, install

npm install create-react-app –global

Create React App is a project to spin up a boilerplate application with React in just one command. It frames the fundamentals of React application with the necessities, including development tooling and a local server, out of the box testing, and a build step to prepare the React application for production.



npm install branch-diff –global

Branch-diff is a CLI tool that diffs two branches in a Git repository and produces a list of differences between two passed branches. The list can either be output as markdown or as console output. This small tool is useful when the developer is working across multiple branches and are looking to get a summary of the differences between the two branches.



npm install nodemon –global

Nodemon is a small utility that will automate restarting a Node.js application when it detects a file change in the directory it runs in. Nodemon is a simple CLI tool that is exceptionally useful when working on a Node.js application and restating quickly – it will cut out the repetitive steps of switching to the terminal, ending the application’s process, and then restarting the application.



npm install localtunnel –global

Localtunnel is a helpful module that will expose an application running on localhost with a single command. For instance, if the developer is working with APIs and needs to provide a public URL, then the developer can use localtunnel to get an online, accessible URL without the need to deploy. Also, it is excellent for collaboration.

NVM – The Node Version Manager


# Since nvm’s not an npm module, you can install with cURL or wget

# Install with cURL:

Curl -o- | bash

# Install with wget:

wget -qO- | bash
NVM is a CLI tool which is exceptionally helpful for Node.js developers. It also allows version management of Node.js. This means the developer can download, swap, and test on any version of Node.js. This is handy for testing modules on the current release line, in addition to the LTS release lines.


Path Module in Node.js

In this article, we are going to discuss building a Path module utility by using one of the module present in the Node.js modules library. There are numerous modules present in Node.js library such as OS module, path modules, net module, DNS module, and domain module. All of these modules are quite popular and used very commonly to build any Node based application.

Node.js Path Module:

1 // Command to import Path Module in Node.js.
3 var path = require(“path”);

Methods present in the Path Module of Node.js:

Below we have listed the basic methods and their descriptions which are present in the Path Module of Node.js.

path.basename (path, ext):

This method of the Path module is used to return the last portion of a path. It is similar to the Unix base name command.

path.dirname (path):

This method of the Path module is used to return the directory name of a path. It is akin to the Unix dirname command.

path.extname (path):

This method of the Path module is used to return the extension of the path, from the last ‘.’ to end of string in the last portion of the path. In the case, when there is no ‘.’ in the last part of the path or the first character of it is ‘.’, then it will return an empty string.

path.isAbsolute (path):

This method of the Path module is used to define whether the path is an absolute path or not. Such an absolute path will always resolve to the same location, regardless of the working directory.

path.join ([path1][, path2][, …]):

This method of the Path module is used to join all the arguments together and regularize the resultant path.


It is a constant that provides access to above-mentioned path methods, but it always interrelates in a way that is win32 compatible.

Illustration on use of Path Module in Node.js Application:

1 // Command to import Path Module in Node.js.
2 var path = require(“path”);
3 //1. Use of path.normalize () method.
4 console.log (‘Path normalization is : ‘ + path.normalize(‘/trail/trail1//doublehash/hash/tab/..’));
5 //2. Use of path.join () method.
6 console.log (‘joint path is : ‘ + path.join(‘/trail’, ‘trail1′, ‘doublehash/hash/’, ‘tab’, ‘..’));
7 //3. Use of path.resolve () method.
8 console.log(‘Path resolve is : ‘ + path.resolve(‘hello-nodejs.js’));
9 //4. Use of path.extname () method.
10 console.log(‘Path extension name is : ‘ + path.extname(‘hello-world.js’));
11 //5. Use of path.isAbsolute method.
12 console.log(‘Is Absolute path? : ‘ + path.isAbsolute(‘/PathModule/PathModule.js’));
13 //6. Use of path.dirname (p) method.
14 console.log(‘Path Directory name is : ‘ + path.dirname(‘/PathModule/PathModule.js’));
15 //7. Use of path.relative (from, to) method.
16 console.log(‘Relative Path is : ‘ + path.relative(‘/PathModule/PathModule.js’, ‘/PathModule/build.gradle’));
17 //8. Use of path.basename () method.
18 console.log(‘Path base name is : ‘ + path.basename(‘/PathModule/PathModule.js’, ‘.js’));
19 //9. Use of path.parse (pathString) () method.
20 console.log(‘Parsed path string is : ‘ + path.parse(‘/PathModule/PathModule.js’));
21 //10. Use of path.format (pathObject) method.
22 console.log(‘Path format is : ‘ + path.format(path.parse(‘/PathModule/PathModule.js’)));


When the user executes the above Node.js code, the user can observe the following output on the console.

1 joint path is : \trail\trail1\doublehash\hash
2 Path resolve is : C:\odesk\Abhishek Thakur\NodeJS\PathModule\hello-nodejs.js
3 Path extension name is : .js
4 Is Absolute path? : true
5 Path Directory name is : /PathModule
6 Relative Path is : ..\build.gradle
7 Path base name is : PathModule
8 Parsed path string is : [object Object]
9 Path format is : /PathModule\PathModule.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)