Category Archives: NODE.JS


String Decoder Module in Node.js


String decoder module in node.js is used to provide an API for decoding buffer object into strings. Also, this decoding is performed in a manner that UTF-8 and UTF-16 characters multibyte coding is preserved. The user might query string module in the following way:

var sd = require(‘string_decoder’).StringDecoder;


String decoder class has two methods which are as follows:


This method is used to return the specified buffer as decoded string. The user passes buffer as the argument in this method. Let’s see an example as given below :

//name of the file : write.js
var stringDecoder = require(‘string_decoder’).StringDecoder;
var sd = new stringDecoder(‘utf8′);
var buff = Buffer(‘data to be buffered’);
//Print the buffered data
//Print the decoded buffer

The user can also run it in the following way too:

>node write.js

<Buffer 64 61 74 61 20 74 6f 20 62 65 20 62 75 66 66 65 72 65 64>

data to be buffered


This method is used to return the remaining of the input stored in internal buffer.

  • buffer <Buffer> | <TypedArray> | <DataView> A Buffer, or TypedArray, or DataView containing the bytes to decode.
  • Returns: <string>

It returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be swapped with substitution characters appropriate for the character encoding.

If the buffer argument is provided, one final call to stringDecoder.write() is done before returning the remaining input.


HTTP Server in Node.js

In previous articles, we’ve introduced you to the most basic Node.js program possible. Node.js is more usually known for creating highly scalable server applications. In this article we will introduce you to a simple HTTP server built atop Node.js.

HTTP Server in Node.js


Start by creating a new file named “web_server.js”. Insert the following code into the file and save it.

var http = require(“http”);
var server = http.createServer(function(request, response) {
response.writeHead(200, {“Content-Type”: “text/html”});
response.write(“<!DOCTYPE “html”>”);
response.write(“<title>Hello World Page</title>”);
response.write(“Hello World!”);
console.log(“Server is listening”);

To start the server, type the following command shown below. If everything works well, the user will see a message that the server is listening. Note that the instance the server attempts to bind to port 80, the standard HTTP port. If this port is already in use, or limited on user’s machine, the user will experience an error.


The next step is to connect to the server using a web browser. Launch the browser of choice, and direct it to either of the following links. In networking terms, local host refers to the machine the user is currently using. The browser should be saying “Hello World!”.



The first thing to notice is the call to require() on line 1. Node.js provides a simple module system with a huge developer community. Node.js programs can load specific modules using the require() method. While many modules must be downloaded, some modules, such as http are included with Node.js installations.

Next, the HTTP server is created using the http module’s createServer() method. Comparable to the most Node.js functions, createServer() takes a callback function as an argument. This callback function is implemented each time the server receives a new request.

The callback function takes two arguments, request and response. The request object contains information about the client’s request. In the same way, the response object is used to return data back to the client.

The callback function begins by calling the response.writeHead() method. This method sends an HTTP status code and a collection of response headers back to the client. The status code is used to specify the result of the request.

Along with the status code, the server returns a number of HTTP headers which define the parameters of the response. If the user does not specify headers, Node.js will implicitly send them for the user.

Next, the server executes several calls to response.write(). These calls are used to write the HTML page. By default, UTF-8 character encoding is used. To be precise, all of these calls could be combined into a single call to improve performance.

After the HTML page has been written, the response.end() method is called. By calling this method, the user is telling the server that the response headers and body have been sent, and that the request has been fulfilled.

The call to listen() causes the server to bind to a port and listen for incoming connections. In order to connect to the server, clients must know exactly which port the server is listening on. Ports are identified by port numbers, with HTTP servers typically listening to port 80.


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