Node.js Event Loop

What is Event in NodeJS? The Events and Callbacks are used in the Node JS to specify concurrency. The Node JS uses the async function to provide concurrency because the Node JS applications are single-threaded applications and Node JS API is asynchronous. The Node thread observes the event loop after completion of every task and it executes the respective event which specifies the event listener function to be executed.

NodeJS Event Loop | Even Driven Programming

The NodeJS uses event-driven Programming that means when the node starts its server it just calls its declared functions, variables and waits for an event to happen. This is one of the reasons why node js is very fast compared to other technologies.

The event-driven application contains the main loop to listen to events and triggers the callback functions when it detects the event.

Node JS event loop diagram

Difference between NodeJS Events and Callbacks

The Events and Callbacks are look alike but the major difference is that the callback function is invoked when the asynchronous function whereas event handles pattern. When an event occurs the listener function starts executing. The event module and EventEmitter class are used to bind events and event listeners because Node JS provides various built-in events.

EventEmitter class to bind Event and Event Listener

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

To bind Event with an Event Handler

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

To Launch an event

//  Launch an event

NodeJS Event Loop Example

// 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.');
// Launch 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.');
// Launch the connection event
console.log("Program Ended.");

NodeJS Event Loop Example Output

After completion of successful code entry, open a command prompt and run the code as node main.js. You will observe the following output.

node js event loop program output

That’s about the NodeJS Event Loop Programming with some examples. Try to create a few more events and know the difference between how the event and callback work in event-driven programming.