Node.js – Event Loop

Node.js – Event Loop

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

Event-Driven Programming

Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur.
In an event-driven application, there is generally a main loop that listens for events, and then triggers a callback function when one of those events is detected.
Although events look quite similar to callbacks, the difference lies in the fact that callback functions are called when an asynchronous function returns its result, whereas event handling works on the observer pattern. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners as follows −

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

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 fire an event programmatically as follows −

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

Example

Create a js file named app.js with the following code −

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
EmitEvent();
function EmitEvent()
{
setTimeout(function(){
eventEmitter.emit('connection');
eventEmitter.emit('onlyonce');
eventEmitter.emit('ready');
EmitEvent();
}, 3000);
}
//subscribe to event exposed by event emitter.
eventEmitter.on('ready', function(){
console.log('ready captured');
});
//subscribe to event exposed by event emitter.
eventEmitter.once('onlyonce', function(){
console.log('onlyonce captured');
});
eventEmitter.once('connection',function(){
console.log("connected successfully");
})

Now let's try to run the above program and check its output −

$ node app.js

IT should produce the following infinite loop −

>node app.js
connected successfully
onlyonce captured
ready captured
ready captured
ready captured
ready captured
ready captured
ready captured
ready captured
ready captured
ready captured
ready captured
ready captured
ready captured
...

How Node Applications Work?

In Node Application, any async function accepts a callback as the last parameter and a callback function accepts an error as the first parameter. Let's revisit the previous example again. Create a text file named test.txt with the following content.

this file has some raw content
for demonstration purpose
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."

Create a js file named app.js having the following code −

var fs = require("fs");
fs.readFile('test.txt',function(err, data){
if (err) return console.error(err);
console.log(data.toString());
});

Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during the read operation, then the err object will contain the corresponding error, else 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.

this file has some raw content
for demonstration purpose
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
Node.js – Callbacks Concept (Prev Lesson)
(Next Lesson) Node.js – Event Emitter