Event Loop in Node JS

E

We learned the callback concept of Node JS in the previous tutorial. This article is in the continuation of the previous and relates events with the event loop, so if you have not gone through the callback concept, it is recommended to grip on the concept first.

How Node JS event work with callback?

Node JS provides concurrency by using the callbacks and events. Although Node JS is a single-threaded application, every API in Node JS maintains asynchronous behavior using async function calls and hence, maintains concurrency.

Basically, the event works with the callbacks. Whenever an async function is called, Node JS keeps an event that loops until a task completes. After the completion of the task, the event is fired which tells the event listener to execute.

What is event driven programming in Node JS?

Node JS is known as an event-driven programming language therefore, it is very fast and concurrent as compared to the other technologies. Whenever the Node server starts, it initializes the variables, declares functions, and then goes into the state where it waits for events. This process is called the event loop.

Callback and event both work to provide a better experience and concurrent responses to the requests. The difference lies between them is that the callback function is called when the async function returns the results.

However, in case of an event, they are fired upon the completion of some task. The function that executes upon the firing of the event is called the event-listener or observer function. In the next section, we will learn the built-in events class provided by Node JS.

Node JS Events Class

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

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

In the above code, we import the event module of Node JS.

EventEmitter class provides the methods to fire the events. We will see them in the next examples.

How to handle event in Node JS?

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

How to fire event in Node JS?

// Fire an event 
eventEmitter.emit('eventName');

Complete example of an event in Node JS

// 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 
   eventEmitter.emit('data_received');
}

// 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 
eventEmitter.emit('connection');

console.log("Program Ended.");

Explanation of the above example

  1. import the event class using require directive.
  2. Create EventEmitter object and make an event handler function in which we somply log some message in the console and then acknowledge that this even handler has recieved the data from the event.
  3. The next step is to bind the event with the event handler.
  4. Next, we create an anonymous function to bind the even handler function with this function.
  5. Lastly, we fire the event using the connection.

Run the above code using the following command and observe the output in the console.

$ node main.js

The above example will output the following result in the console.

connection successful.
data received successfully.
Program Ended.

Working of Node JS application

In the Async function in Node JS, the last parameter is the callback function and the callback function itself accepts the error object as its first parameter.

Create a text file with the sample content below and recall the previous example.

NodeJsTutor is giving self learning content
to teach the world in simple and easy way!!!!!

Create a JS file and name it main.js with the following piece of code.

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err) {
      console.log(err.stack);
      return;
   }
   console.log(data.toString());
});
console.log("Program Ended");
  1. In the above code, we import the fs class using require directive. fs class provides functions to work with the files.
  2. The callback function recieves the data from the readFile function in the data object and in case of any error returned by the readFile function, it goes to the first parameter of the callback function, that is error parameter.
  3. The callback function parse the content of the text file and simply log it in the console.
  4. The above example produce following results.
Program Ended
NodeJsTutor is giving self learning content
to teach the world in simple and easy way!!!!!

Introduction to event loop official documentation in Node JS

About the author

Tutor Network Team

Add comment

Tutor Network