We now have a youtube channel. Subscribe!

Node.js | Event Loop

Node.js | Event Loop

Hello folks! welcome back to a new edition of our tutorial on Node.js. In this section of our tutorial on Node.js, we will be studying about Node.js Event Loop.

Node.js is a single-threaded application, but it can support concurrency via the concepts of event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they utilize asynchronous function calls to maintain concurrency. Node uses observer pattern. Node.js thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which prompts the event-listerner function to execute.

Event-Deriven Programming

Node.js makes heavy use of events and it is also one of the reasons why Node.js is very fast compared to other similar frameworks. As soon as Node begins its server, it simply initiates its variables, declares functions and then simply waits for the event to happen.

In an event-driven web application, there is generally a main loop that listen for events, and then trips a callback function when one of those events is detected.

Events in Node.js

Although events looks similar to callbacks, the difference lies in the fact that callback functions are called when an asynchronous function returns its result, but event works on the observer pattern. The functions that listen to events act as Observers. Whenever an event gets triggered, its listener function starts executing. Node.js has multiple built-in events obtainable through event module and the EventEmitter class which are used to bind events and event-listeners as shown below -

// Import events module
var events = require('events');

// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();


The following is the syntax to bind an event handler with an event -

// Bind event and event  handler as follows
eventEmitter.on('eventName', eventHandler);

We can trigger an event programmatically as follows -

// Fire an event 


Create a js file, main.js using the following code -

// Import events module
var events = require('events');

// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

// Create an event handler as follows
var connectHandler = function connected() {
   console.log('connection succesful.');
   // Fire the data_received event 

// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function() {
   console.log('data received succesfully.');

// Fire the connection event 

console.log("Program Ended.");

Now, let us try running the above code and check its output -

$ node main.js


When the above program is executed, it will produce the following result -

connection successful.
data received successfully.
Program Ended.

How Node Application Works?

In Node program, an asynchronous function accept a callback as the last parameter and a callback function accepts an error as the first parameter. Let's run through the earlier example again. Create a file, input.txt using the following content -

WebDesignTutorialz is offering self learning content
to teach the world in simple and easy manner!!!!!

Create a js file, main.js having the following code -

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err) {
console.log("Program Ended");

Here, fs.readFile() is a async function whose purpose is to read a file. If an error happens during the read operation, then the err object is going to contain the corresponding error, otherwise data will contain the contents of the file. readFile passes err and data to the callback function after the read operation is complete, which finally prints the content.

Program Ended
WebDesignTutorialz is offering self learning content
to teach the world in simple and easy manner!!!!!

Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be studying about Node.js Event Emitter.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain