Node.JS Event Mechanism

As mentioned earlier, node.js applications are single threaded. A questions arises here that how come node.js implements concurrency in single threaded. The answer lies in events and callbacks. In this article we shall study node.js event mechanism. An event occurs in response to a specific action or completion of task. For instance when a user clicks on a button an event is fired, similarly when file reading is complete an event is fired etc. The events corresponding to the actions are kept in an event loop. As soon as a task which can fire an event completes, events are fired via callback mechanism. These events are handled by corresponding event handlers.

Actually the speed and concurrency with which a node.js application executes owe itself to these events. As soon as you start a node.js application it declares its variables, initializes the functions and start executing its normal flow, in parallel it generates an event loop which keeps checking if an event has fired.

Event Generation and Handling

There are four steps involved in event generation and handling life cycle. They have been enlisted below.

  • Import “events” module
  • Create an eventEmitter object via events module.
  • Bind the event with the event handler via this eventEmitter “on” method
  • Finally fire an event which will be handled by the event handler.

Node.js Event Mechanism Example

Let’s have a look at a simple example of event generation and handling in node.js

var event = require('events');

var eE = new event.EventEmitter();

var conHandler = function connected() {
   console.log('connection creation passed.');

eE.on('connection', conHandler);
eE.on('data_complete', function(){
   console.log('data received succesfully.');


console.log("Program execution completed.");

Download the code Try the code

In the above code we first import events module and stored the resulted events object in event variable. Using this event variable we create eventEmitter object eE. We then created an event Handler “conHandler” which first displays the message about connection successful and then fires another event i.e “data_complete”. Next, we use eventEmitter objects on function to bind connection event with conHandler and “data_complete” event with anonymous function. Finally we fire “connection” event via eventEmitter’s “emit” function. This executes the “conHandler” function which displays a message and then fires “data_complete” event which executes he anonymous function that displays message about successful data received.

Node.JS Callback Mechanism

In one of the earlier articles, where we studied the features of Node.js, we said that node.js follows event-driven and non-blocking model thanks to node.js callback mechanism. However, we did not delve into callbacks in detail. In this article we will dig deeper into callbacks. We shall study what callbacks are and how they help in implementing non-blocking code.

Callbacks are basically asynchronous functions that are called whenever a certain task is completed. Almost of all of the node.js modules and libraries have call back functions.

Let’s explain callbacks with the help of an example. Suppose, you have some piece of code which reads content of the text file. After the code you print a statement on the command window. In case of blocking code, your program will first read all the contents of the fall and then print the statement on the screen. This is blocking code, your code blocks and doesnt further execute unless all the contents of the file have been read. On the other hand, in case of non-blocking code, once the call to read the content of the file is made, the callback function is also specified and the next line of the code is executed without blocking the code for complete reading of file content. Finally, when he contents of the file have been read, the corresponding callback function executes.

Blocking Code Example

Create a text file named “myfile.txt” and add the following text in the file.

Knowledge hills is a website that contains free of cost programming tutorials

Learn and Build apps for free.

Now create a file named “blocking.js” in the same directory as “myfile.txt” and add the following line of code in it.

var filestream = require("fs");

var content = filestream.readFileSync('myfile.txt');

console.log("Code after file read");

Download the code

In the above code we have used “readFileSync” method of the file stream module “fs”. This method is synchronous and reads the content of the file in blocking mode. Now run the above file using “node blocking.js”. In the output you shall see that first the content of the file are printed on the screen and then the message after the “readFileSync” function is printed on the screen.

Non-blocking Code Example

Now let’s see how we can read the contents of the file in non blocking manner. Again create a file named “nonblocking,js”. The contents of the file are as follows.

var filestream = require("fs");

filestream.readFile('myfile.txt', function (error, content) {
   if (error) return console.error(error);

console.log("Code after file read");

Download the code

In the above case, you shall see that the call for reading file will be sent and then immediately after that the message below the call shall be printed. Once the file reading completes the callback function prints the contents of the file. This is how node.js callback mechanism works.


In the last article we studied how to use REPL Terminal to execute basic node.js code through command window. In this article we are going to study node.js NPM which is another very handy tool. Node.js NPM stands for node.js package manager and it has two primary tasks. 1) It is used to download node.js packages available at 2) It provides a command line interface to install these modules, maintain versioning and dependency issues. It has almost same functionalities as nuget package manager has in visual studio.

NPM comes bundled with node.js by default. To check the current version of NPM installation, simply type “npm –version” on the command prompt.

Installing a Package via Node.js NPM

It is very easy to install any package via npm. You simply have to write “npm install ” in the command window. For instance, to install “express” module which is one of the most famous node.js web frameworks, simply type the following command “npm install express”. This will install the express module inside a directory named “node_modules” which is inside the directory where you currently running the node.js command window. This is local installation. You can get all the local modules via command “npm ls”. Now you can access local modules via var exp = require(‘express’) command.

The packages installed via “npm install ” are installed locally. Which means that they are installed in the directory where the node.js application is currently running. You can also install node.js modules globally via “npm install -g”. This will install the package in the global system directory.

Uninstalling a Package

Uninstalling a node.js package is extremely simple. You have to use “npm uninstall ” command. You can verify if the package has actually been uninstalled by checking the directory where it was installed or by listed the packages via “npm ls” command.

Updating a Package

To update a package, simply type “npm update .”

Search a Package

Similarly, you can also search installed packages. To do so, type “npm search . This will return the package if exists.”

Node.JS REPL Terminal

Till now what we have been doing is that we create our node.js application in a text editor, save the file with “.js” extension and then run the file via node.js command prompt. This sounds a bit cumbersome for small tasks such as adding two numbers, printing a string on screen etc. The ideal case would be window where we can directly add or subtract numbers, display their results and perform other similar tasks. Luckily enough for us we have built-in node.js REPL terminal which performs such tasks.

REPL is an environment similar to command prompt. Here you can directly enter commands that will be processed and executed by REPL terminal. REPL terminal stands for Read-Evaluate-Print-Loop and has four parts as the name suggests. REPL terminal first reads the user input then evaluates it and stored it in appropriate node.js data structure. It then processes the input and prints it. The process keeps looping until the user presses Ctrl + C twice.

Working wit Node.js REPL Terminal

To open node.js REPL terminal, simply type “node” in command window. This starts the REPL terminal. Now you can perform all sorts of tasks in this terminal.

Executing Mathematical Expressions

You can execute simple, as well as complex mathematical operations in REPL terminal. take a look at the following figure.


In the above image, 1 is added to 3 which is equal to 4. Similarly a more complex expression is evaluated which results in 12.

Variables in REPL

It is extremely simple to create variables in REPL, you can use any name for the variable and store any value in it. The value will also be printed on the next line. However, if you use keyword “var” before the name of the variable, the value is not printed it is only stored inside the variable. Take a look at the following screenshot.


Take a look at the above code, here created num1 and num2 variable with and without var keyword, respectively. Also we have used “_” which basically stores the last result.

Multiline Expressions

Multiline expressions are the expressions that span across multiple lines. Take a look at the following code snippet.


In the above code snippet, a while loop prints the table of seven on the console log.

Node.js Simple Application

If you are reading this, it means you have a theoretical understanding of Node.js and you have installed local node.js environment. However, if you haven’t installed a local environment, I would recommend you to read the last article. In this article we are going to develop a node.js simple application.

Major Components of a Node.js Application

There are three major components of any node.js application.

1) Importing Modules

Node.js comes with variety of built-in modules which contain different functionalities. In order to use that functionality, you need to import the module first. In node.js “required” command is used to import the desired modules.

2) Creating a Server

The second major component of a node.js application is a server which listens to requests on a specific port. Server receives request from the client, processes it and returns the response.

Sending a Request

The third and final component of a node.js application is the request to the server. Request can be sent to a server via console client or web browser.

Node.js Simple Application

In the upcoming section, we shall create a simple node.js application that will contain a server and it will respond to the requests generated by clients. Take a look at the following code.

var http = require("http");

http.createServer(function (request, response) {

   response.writeHead(200, {'Content-Type': 'text/plain'});
   // Send the response body as "Welcome to knowledge hills"
   response.end('Welcome to knowledge hills\n');

// Console will print the message
console.log('Server listening for requests at');

Download the code

Now take a careful look at the above code. It contains a line “var http = require(“http”);”. Here we are importing the required “http” module. This “require” call returns an HTTP instance which is stored in the “http” variable.

Next we call the createServer function on the http instance. This creates another function as a parameter which implements the request and response model. At the end of the createServer() method call we append the listen(9006) which specifies the port on which the server will listen.

We know that node.js applicationsa are non-blocking, therefore once we call the createServer() method and it starts listening for the requests, the control shifts to the next line of code where we can execute anything. In the above code we simply display a message via console.log.

Now inside the function, we send response when client requests is received. In response we end the header whose first parameter is 200 which means that status is okay. Next we specify the type of content that the server will send. And finally we send he response.end() method to send the response body.

To execute the above code, simply execute the above application via command prompt. A message shall appear on command prompt that ‘Server listening for requests at’. This means that server is successfully running. Now open your browser and type this address “”. On the web page that opens, you shall see the following message “Welcome to knowledge hills”. Hence, this is how we create node.js simple application. Happy Coding!

Node.JS Environment Setup

In the last two articles we introduced you to Node.JS. We covered what Node.js is and what are some of its major features. In this article, we are going to study the node.js environment setup process. Though, you can run your code online as well, but if you are looking for some serious node.js development, you must set up a local environment.

To write and execute a node.js application on your local machine, you need a couple of software: A text editor and binary installables of node.js. You can use any text editor. I recommend using Notepad++ or Brackets. They are totally free.

You simply have to type the Node.js code in a text file and save it with “.js” extension. Now in order to execute this code, you need node.js binary installables. The process of downloading and installing these libraries has been explained in the next section.

Downloading and Installing Node.js

Go to this Download link and download the corresponding download file depending upon your operating system. I shall explain the download and installation process for windows. For windows OS, download the “.msi” window installer. Follow the installation process. By default, node.js will be installed in the “C:\Program Files\nodejs\” directory. Also, the installer will set the enviroment’s path varianble to C:\Program Files\nodejs\bin

Sanity Check for Installation

Now in order to see if node.js has been correctly installed and is working without an error, create a text file named myapp.js and add the following code to the file “console.log(“Welcome to Knowledge Hills.”)”. Now open the command prompt and type “node myapp.js”. You should see “Welcome to Knowledge Hills.” printed in the command window if everything goes fine. Please mention full path to the “myapp.js” file after you type node command in the prompt window. If command prompt throws an error or it doesn’t display the message “Welcome to Knowledge Hills.” on the command prompt, your installation wasn’t successful. In that case, I would advise you to repeat the process.

In this article we discussed how accomplish node.js environment setup. In the next article we shall create our first node.js application. So keep visiting this site and Happy Coding!!!

Node.JS Features

The last article provided a brief introduction to node.js. In this article we shall study some of the most amazing node.js features. When you download node.js (which I will show in the next article) it comes with a node.js runtime enviroment and some prebuild JavaScript. The runtime environment is used to compile and execute node.js programs while the JavaScript library contains commonly used functionalities. In the following sections, we shall study some of the fundamental node.js features followed by it uses.

Common Node.js Features

Following are some of the major features of node.js

Fast Execution

Node.js is written in C/C++ since it uses Chrome’s V8 engine which is also written in C/C++. This makes Node.js extremely fast.

Asynchronous and Non-Blocking

Node.js applications are asynchronous and non-blocking. It means that whenever node.js application sends an API call, it doesnt wait for the API to return data. Rather, specifies a call back function for the previous call and moves to the next API call. When the data from the previous API call is returned, the call back function for the previous call executes. This way, node.js applications execute in a non-blocking manner.


Though node.js applications are single threaded, still owing to their non-blocking and asynchronous nature, they can be easily scaled to perform multiple task simultaneously.

Zero Buffering

Node.js applications retrieve and process data in real time without storing any data in memory buffers. This is what makes node.js ideal for developing streaming applications

Some applications of Node.js

Node.js has become extremely popular in recent era. Currently many big companies like Microsoft, Yahoo, Uber, GoDaddy, Ebay etc are using node.js in their applications. Node.js applications are ideal for the following type of applications.

  • Single Page Applications
  • Data Streaming Applications
  • JSON Based Applications
  • Data Intensive Real time Applications
  • I/O Intensive Applications

However, if you are developing an application that involves lots of complex processing, it is not advisable to use node.js applications.

This article explained some of the major node.js features. In the next article, we shall see how to setup local environment in order to run node.js applications.

Node.JS Introduction

Welcome to yet another exciting series of tutorials on node.js. In this series, we shall cover basic as well as advanced node.js concepts. We shall start with very basics and will build upon the knowledge gained in the previous articles as we move forward towards more advanced concept. This article contains node.js introduction.


It is pertinent to mention here that this series is not for novice web developers. You must possess substantial HTML, CSS, JavaScript knowledge before you can proceed to learn node.js. If you are not familiar with any of these technologies, I suggest you to first study these technologies and then come back. However, if you have ample knowledge of the aforementioned technologies, I assure you have made an excellent choice to study node.js.

What is Node.js

Node.js is a server side JavaScript framework. Well this might surprise you because all our lives we have been told that JavaScript it a client side technology that runs within a browser. However, node.js is different from other JavaScript framework/libraries in both ways. Firstly, node.js is a server side technology, and secondly it can be run outside of the browser. Isn’t this amazing? Running JavaScript without a browser? Well, node.js has this capability. Node.js uses Google Chrome’s V8 engine for program execution. It is totally open source

When to use Node.js

Node.js is extremely suitable for I/O extensive applications such as chat server, video streaming program and distributed/network applications. Node.js is based on non-blocking and event driven programming model which makes it ideal for realtime and distributed applications.

How to Execute Code Samples?

In one of the upcoming articles, I shall explain the process of installing node.js locally on your machines. You can simply copy and paste code samples from the articles, or download them and execute them on your own machines, Apart from that, we have set up an online execution environment where you can simply click “run code” link below each code sample and see the output of the code on the fly. You can also modify the code at run time and see its effect immediately in the execution window.

This article provided a brief node.js introduction. In the next article, we shall discuss some of the major features of node.js along with its advantages and disadvantages.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .