top
upGrad KnowledgeHut SkillFest Sale!

Search

Node JS Tutorial

Node.js is an asynchronous, event-driven, non-blocking I/O application. It is built with a V8 engine along with other node core components like Libuv. Libuv library developed in C++ provides event loop mechanism and I/O API for concurrent operations. Thanks to this multithreading language which helps in handling concurrent tasks. This mechanism makes Node.js an asynchronous event-based platform in which everything is a reaction to an event.Above diagram gives a glimpse of how Node.Js works and will use it to understand the event loop better. Node.js is a single thread application and all the blocking calls are stored in the call stack and once they are processed they are removed from the call stack.  Let's take an example: Console.log(‘hi’); //1 Console.log(‘welcome’); //2 Console.log(‘Happy learning’); //3 When we run a node, line 1 is moved to call stack and executed and then followed up by line 2 and then line 3. A similar thing can be observed if an error is raised then from the error stack, we can know the order of execution. Node.js provides timer functions globally. We can work with Node.js asynchronously is through using the timing functions. The timing functions setTimeout, clearTimeout, setInterval, and clearInterval work the same way they do in the browser and are available to you globally.  So whenever asynchronous calls are observed during execution, those are moved to API block and the call stack is continued. When the asynchronous operation is done say setTimeout, the execution of call-backs is done by the event loop i.e. it moved the callback of setTimeout to Event Queue. And event loop will be keeping monitoring the call stack to get empty. And once it is empty then call back is pushed to call stack and executed. Note: Libuv library basically creates a thread pool to offload the asynchronous work. If the operating system provides an interface for I/O tasks then this is used instead of working with threads. Below are the examples of global timer functions: App1:  Simple example using setTimeout with a callback to log in console. Create a timer.js file Add a variable say ‘waitTime’ with 3 seconds i.e. 3000 in milliseconds. Let's use setTimeout to wait for 3 seconds and console.log in a callback which gets executed after a delay. var waitTime = 3000;  console.log(“wait for it”); setTimeout(() => console.log(“done”), waitTime); This setTimeout is going to make application wait for 3 seconds and then it will invoke the callback. Let's go to terminal and run node timer.js to observe that application waited 3 seconds after logging the first message and done. So during these three seconds while we're waiting for our application is going to be running.  App2:  Extending above example with usage of setInterval along wit  Let's extend the above one with setInterval function. Add a couple more variables say currentTime which we can initialize it to 0 milliseconds and waitInterval with 500 (half a second). WaitInterval is used to fire the callback of setInterval every half second.  var waitTime = 3000;  var currentTime = 0;  var waitInterval = 500;  console.log(“wait for it”);  setTimeout(() => console.log(“done”), waitTime); setTimeout waits for a delay once and then invokes the callback function, where as setInterval will fire the callback function over and over again on an interval time. Lets add a setInterval. var waitTime = 3000;  var currentTime = 0;  var waitInterval = 500;  console.log(“wait for it”);  setInterval(() => {  currentTime =+ waitInterval;  console.log(`waiting ${currentTime/1000} seconds…`); // to display in seconds  }, waitInterval);  setTimeout(() => console.log(“done”), waitTime); run node timer.js We will observe that waiting is keeping incrementing by half second and once we reach 3 seconds, done is displayed. Notice that after the done log we are still going. That interval will not stop. Lets add an exit criteria after 3 seconds and to stop application hit control C. setInterval return has to be set in a variable. And call clearInterval with argument as this variable inside setTimeOut. var waitTime = 3000;  var currentTime = 0;  var waitInterval = 500;  console.log(“wait for it”);  var interval = setInterval(() => {  currentTime =+ waitInterval;  console.log(`waiting ${currentTime/1000} seconds…`);  }, waitInterval);  setTimeout(() => {  clearInterval(interval);  console.log(“done”)  }, waitTime); Now on running node timer.js, we will see that post 3 seconds the application is stopped. App3: Let's modify this code to display the time waiting in a percentage and also control the standard output, so that we overwrite the last line, meaning that we can see a percentage number grow. Lets add a function for writing the percentage writeWaitingPercent.  function writeWaitingPercent(percent) {      process.stdout.clearLine(); // clears the previous line      process.stdout.cursorTo(0); // moves the cursor to first line      process.stdout.write(`waiting ... ${percent}%`); // add the text to first line  } Lets add a variable to percentWaited and set to 0 Call the writeWaitingPercent with percentWaited at the end of the file Also updated the setTimeOut to call this writeWaitingPercent with 100 in callback. setTimeout(() => {  clearInterval(interval);  writeWaitingPercent(100);  console.log(“done”)  }, waitTime); In setInterval callback also, lets call the writeWaitingPercent based on the calculated percentWaited based on currentTime. var interval = setInterval(() => {  currentTime =+ waitInterval;  percentWaited = Math.floor((currentTime/waitTime) * 100);  writeWaitingPercent(percentWaited);  }, waitInterval); Lets run node timer in terminal observe the percentage increase.  To observe a slow increase we can reduce the waitInterval to much lesser value say 50 milliseconds. varwaitTime = 3000;  varcurrentTime = 0;  varwaitInterval = 500;  varpercentWaited = 0;  functionwriteWaitingPercent(percent) {  process.stdout.clearLine();  process.stdout.cursorTo(0);  process.stdout.write(`waiting ... ${percent}%`);  }  varinterval = setInterval(function() {  currentTime += waitInterval;  percentWaited = Math.floor((currentTime/waitTime) * 100);  writeWaitingPercent(percentWaited);  }, waitInterval);  setTimeout(function() {  clearInterval(interval);  writeWaitingPercent(100);  console.log("\n\n done \n\n");  }, waitTime);  writeWaitingPercent(percentWaited); Output: node timers  waiting ... 100%  done EventEmitter EventEmitter is another core module which comes along with Node.js. It helps in build a pub sub pattern i.e. to emit and listen to custom events. Lets use this module and understand with the help of an example. App1: Lets create an event.js file and create a new variable events to import this module. const events  = require(“events”); Create an instance of the event emitter. const emitter = new events.EventEmitter(); We can emit an event using this emitter and event name be ‘CustomEvent’ and from node. emitter.emit(“CustomEvent”, “Raising a custom event”, “node”); Now, we need to capture this event and handle which can be done using the same emitter. emitter.on(“CustomEvent”, (msg, user) => console.log(`${user}:${msg}`)); This has to be declared before emitting the event. Open the terminal and run node events Output has to be Raising a custom event. App2: One other important about these events is that they are asynchronous and raised when they happen. Let take another example. Taking the above example. Let's listen to the user inputs and react to it.  process.stdin i.e. readable stream helps in listening to data input. process.stdin.on(“data”, data => { }); Remove the code from previous example code related to emitting of custom event. In the callback of it, let's emit the customEvent with the data entered by the user. process.stdin.on(“data”, data => {       const input = data.toString().trim();        emitter.emit(“customEvent”, input, “terminal”);  }); If user enters ‘exit’, then lets exit the process by emiting that user has exited. process.stdin.on(“data”, data => {       const input = data.toString().trim();        if (input === ‘exit’) {            emitter.emit(“customEvent”, “user has exited”, “terminal”);            process.exit();        }        emitter.emit(“customEvent”, input, “terminal”);  }); Remove the code from previous example code related to emitting of custom event. run node events in the terminal Now the terminal is waiting for user inputs and not exiting. This is because the process.stdin is waiting for the data. Enter the text says ‘hello event emitter’ The output should be terminal: hello event emitter. On entering the ‘exit’ text it should exit the process. App3: Let's create an object and add event handling mechanism to that object with the help of eventEmitter. Create a customEventObject.js file Import the event emitter using the required module. const eventEmitter = require(“events”).EventEmitter; Create a person object. var person = (name) => { this.name = name;  } We want the eventEmitter to be inherited by this person object. We can actually use the util module that is part of node.js for inheriting. At the top of the file, get util using require a module. const util = require(“util”); Util module has a function called inherits where we can add an object to a prototype of another existing object and that’s how inheritance works in JS. util.inherits(person, EventEmitter); Above line has just had person object inherit the eventEmitter and thereby providing the functionality to emit and listen to events.  Let's create an instance of this person object var employee = new Person(‘SomePerson’); Now, this employee can listen to any events. So let's add an event handler on this object. employee.on(‘programmer’, (msg) => { console.log(`${this.name}`: ${msg});  }); Let's raise an event using emit. employee.emit(‘programmer’, ‘You are a good learner’); Save and run the node customEventObject.js in terminal The output should be, SomePerson: You are a good learner. varEventEmitter = require('events').EventEmitter;  varutil = require('util');  varPerson = function(name) {  this.name = name;  };  util.inherits(Person, EventEmitter);  varemployee = newPerson("SomePerson");  employee.on('programmer', function(msg) {  console.log(`${this.name}: ${msg}`);  });  employee.emit('programmer', "You are a good learner."); Output: SomePerson: You are a good learner.
logo

Node JS Tutorial

Node JS Events

Node.js is an asynchronous, event-driven, non-blocking I/O application. It is built with a V8 engine along with other node core components like Libuv. Libuv library developed in C++ provides event loop mechanism and I/O API for concurrent operations. Thanks to this multithreading language which helps in handling concurrent tasks. This mechanism makes Node.js an asynchronous event-based platform in which everything is a reaction to an event.

Node JS Events

Above diagram gives a glimpse of how Node.Js works and will use it to understand the event loop better. Node.js is a single thread application and all the blocking calls are stored in the call stack and once they are processed they are removed from the call stack.  Let's take an example: 

  • Console.log(‘hi’); //1 
  • Console.log(‘welcome’); //2 
  • Console.log(‘Happy learning’); //3

When we run a node, line 1 is moved to call stack and executed and then followed up by line 2 and then line 3. A similar thing can be observed if an error is raised then from the error stack, we can know the order of execution. 

Node.js provides timer functions globally. We can work with Node.js asynchronously is through using the timing functions. The timing functions setTimeout, clearTimeout, setInterval, and clearInterval work the same way they do in the browser and are available to you globally.  

So whenever asynchronous calls are observed during execution, those are moved to API block and the call stack is continued. When the asynchronous operation is done say setTimeout, the execution of call-backs is done by the event loop i.e. it moved the callback of setTimeout to Event Queue. And event loop will be keeping monitoring the call stack to get empty. And once it is empty then call back is pushed to call stack and executed. 

Note: Libuv library basically creates a thread pool to offload the asynchronous work. If the operating system provides an interface for I/O tasks then this is used instead of working with threads. 

Below are the examples of global timer functions: 

App1:  Simple example using setTimeout with a callback to log in console. 

  • Create a timer.js file 
  • Add a variable say ‘waitTime’ with 3 seconds i.e. 3000 in milliseconds. 
  • Let's use setTimeout to wait for 3 seconds and console.log in a callback which gets executed after a delay. 
var waitTime = 3000; 
console.log(“wait for it”); 

setTimeout(() => console.log(“done”), waitTime); 

  • This setTimeout is going to make application wait for 3 seconds and then it will invoke the callback. 
  • Let's go to terminal and run node timer.js to observe that application waited 3 seconds after logging the first message and done. 
  • So during these three seconds while we're waiting for our application is going to be running.  

App2:  Extending above example with usage of setInterval along wit  

  • Let's extend the above one with setInterval function. 
  • Add a couple more variables say currentTime which we can initialize it to 0 milliseconds and waitInterval with 500 (half a second). 
  • WaitInterval is used to fire the callback of setInterval every half second.  
var waitTime = 3000; 
var currentTime = 0; 
var waitInterval = 500; 
console.log(“wait for it”); 
setTimeout(() => console.log(“done”), waitTime); 
  • setTimeout waits for a delay once and then invokes the callback function, where as setInterval will fire the callback function over and over again on an interval time. Lets add a setInterval. 
var waitTime = 3000; 
var currentTime = 0; 
var waitInterval = 500; 
console.log(“wait for it”); 
setInterval(() => { 
currentTime =+ waitInterval; 
console.log(`waiting ${currentTime/1000} seconds…`); // to display in seconds 
}, waitInterval); 
setTimeout(() => console.log(“done”), waitTime); 
  • run node timer.js 
  • We will observe that waiting is keeping incrementing by half second and once we reach 3 seconds, done is displayed. 
  • Notice that after the done log we are still going. That interval will not stop. 
  • Lets add an exit criteria after 3 seconds and to stop application hit control C. 
  • setInterval return has to be set in a variable. And call clearInterval with argument as this variable inside setTimeOut. 
var waitTime = 3000; 
var currentTime = 0; 
var waitInterval = 500; 
console.log(“wait for it”); 
var interval = setInterval(() => { 
currentTime =+ waitInterval; 
console.log(`waiting ${currentTime/1000} seconds…`); 
}, waitInterval); 
setTimeout(() => { 
clearInterval(interval); 
console.log(“done”) 
}, waitTime); 
  • Now on running node timer.js, we will see that post 3 seconds the application is stopped. 

App3: 

Let's modify this code to display the time waiting in a percentage and also control the standard output, so that we overwrite the last line, meaning that we can see a percentage number grow. 

  • Lets add a function for writing the percentage writeWaitingPercent.  
function writeWaitingPercent(percent) { 
    process.stdout.clearLine(); // clears the previous line 
    process.stdout.cursorTo(0); // moves the cursor to first line 
    process.stdout.write(`waiting ... ${percent}%`); // add the text to first line 
} 
  • Lets add a variable to percentWaited and set to 0 
  • Call the writeWaitingPercent with percentWaited at the end of the file 
  • Also updated the setTimeOut to call this writeWaitingPercent with 100 in callback. 
setTimeout(() => { 
clearInterval(interval); 
writeWaitingPercent(100); 
console.log(“done”) 
}, waitTime); 
  • In setInterval callback also, lets call the writeWaitingPercent based on the calculated percentWaited based on currentTime. 
var interval = setInterval(() => { 
currentTime =+ waitInterval; 
percentWaited = Math.floor((currentTime/waitTime) * 100); 
writeWaitingPercent(percentWaited); 
}, waitInterval); 
  • Lets run node timer in terminal observe the percentage increase.  
  • To observe a slow increase we can reduce the waitInterval to much lesser value say 50 milliseconds. 
varwaitTime = 3000; 
varcurrentTime = 0; 
varwaitInterval = 500; 
varpercentWaited = 0; 
functionwriteWaitingPercent(percent) { 
process.stdout.clearLine(); 
process.stdout.cursorTo(0); 
process.stdout.write(`waiting ... ${percent}%`); 
} 
varinterval = setInterval(function() { 
currentTime += waitInterval; 
percentWaited = Math.floor((currentTime/waitTime) * 100); 
writeWaitingPercent(percentWaited); 
}, waitInterval); 
setTimeout(function() { 
clearInterval(interval); 
writeWaitingPercent(100); 
console.log("\n\n done \n\n"); 
}, waitTime); 
writeWaitingPercent(percentWaited); 

Output: 

node timers 
waiting ... 100% 
done 

EventEmitter 

EventEmitter is another core module which comes along with Node.js. It helps in build a pub sub pattern i.e. to emit and listen to custom events. Lets use this module and understand with the help of an example. 

App1: 

  • Lets create an event.js file and create a new variable events to import this module. 
  • const events  = require(“events”); 
  • Create an instance of the event emitter. 
  • const emitter = new events.EventEmitter(); 
  • We can emit an event using this emitter and event name be ‘CustomEvent’ and from node. 
  • emitter.emit(“CustomEvent”, “Raising a custom event”, “node”); 
  • Now, we need to capture this event and handle which can be done using the same emitter. 
  • emitter.on(“CustomEvent”, (msg, user) => console.log(`${user}:${msg}`)); 
  • This has to be declared before emitting the event. 
  • Open the terminal and run node events 
  • Output has to be Raising a custom event. 

App2: 

One other important about these events is that they are asynchronous and raised when they happen. Let take another example. 

  • Taking the above example. 
  • Let's listen to the user inputs and react to it.  process.stdin i.e. readable stream helps in listening to data input. 
  • process.stdin.on(“data”, data => { }); 
  • Remove the code from previous example code related to emitting of custom event. 
  • In the callback of it, let's emit the customEvent with the data entered by the user. 
  • process.stdin.on(“data”, data => { 
      const input = data.toString().trim(); 
      emitter.emit(“customEvent”, input, “terminal”); 
}); 
  1. If user enters ‘exit’, then lets exit the process by emiting that user has exited. 
  2. process.stdin.on(“data”, data => { 
      const input = data.toString().trim(); 
      if (input === ‘exit’) { 
          emitter.emit(“customEvent”, “user has exited”, “terminal”); 
          process.exit(); 
      } 
      emitter.emit(“customEvent”, input, “terminal”); 
}); 
  • Remove the code from previous example code related to emitting of custom event. 
  • run node events in the terminal 
  • Now the terminal is waiting for user inputs and not exiting. This is because the process.stdin is waiting for the data. 
  • Enter the text says ‘hello event emitter’ 
  • The output should be terminal: hello event emitter. 
  • On entering the ‘exit’ text it should exit the process. 

App3: 

Let's create an object and add event handling mechanism to that object with the help of eventEmitter. 

  • Create a customEventObject.js file 
  • Import the event emitter using the required module. 
  • const eventEmitter = require(“events”).EventEmitter; 
  • Create a person object. 
  • var person = (name) => { 
this.name = name; 
} 
  • We want the eventEmitter to be inherited by this person object. We can actually use the util module that is part of node.js for inheriting. 
  • At the top of the file, get util using require a module. 
  • const util = require(“util”); 
  • Util module has a function called inherits where we can add an object to a prototype of another existing object and that’s how inheritance works in JS. 
  • util.inherits(person, EventEmitter); 
  • Above line has just had person object inherit the eventEmitter and thereby providing the functionality to emit and listen to events. 
  •  Let's create an instance of this person object 
  • var employee = new Person(‘SomePerson’); 
  • Now, this employee can listen to any events. So let's add an event handler on this object. 
  • employee.on(‘programmer’, (msg) => { 
console.log(`${this.name}`: ${msg}); 
}); 
  • Let's raise an event using emit. 
  • employee.emit(‘programmer’, ‘You are a good learner’); 
  • Save and run the node customEventObject.js in terminal 
  • The output should be, SomePerson: You are a good learner. 
varEventEmitter = require('events').EventEmitter; 
varutil = require('util'); 
varPerson = function(name) { 
this.name = name; 
}; 
util.inherits(Person, EventEmitter); 
varemployee = newPerson("SomePerson"); 
employee.on('programmer', function(msg) { 
console.log(`${this.name}: ${msg}`); 
}); 
employee.emit('programmer', "You are a good learner."); 

Output

SomePerson: You are a good learner. 

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. JavaScript was first known as LiveScript. Later on, Netscape changed its name to JavaScript because of its popularity and the excitement generated by it. JavaScript is lightweight and most commonly used as a part of web pages supported by most web browsers like Chrome, Internet Explorer, Opera, Safari, Edge, and Firefox.
JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. Jav...

Read More

Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introduced by Google corporation in 2012 and was considered to be one of the most promising among JavaScript frameworks. It was written completely in JavaScript to separate an application’s logic from DOM manipulation, aiming at dynamic page updates. Angular introduced many powerful features enabling the developer to effortlessly create rich and single-page applications.Topics CoveredThis Angular tutorial will span over eight modules, each module covering numerous individual aspects that you need to gain complete information about Angular. This set of modules serves as an Angular tutorial for beginners along with experienced IT professionals.Here are the topics that will be covered in the Angular tutorial:Get started with Angular.Learn the basics of Angular.Know what Angular Directives.Get an idea of Component Inputs and Outputs of Angular.Know about Forms in Angular.About Services in Angular.Pipes in Angular.HTTP, Routing and Building in Angular.Who can benefit from this tutorial?This Angular tutorial will be helpful to IT professionals such as:Software Developers, Web Application Programmers and IT Professionals Software Architects and Testing Professionals Career aspirants in web development
Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introdu...

Read More

USEFUL LINKS