Skip to content

Better understand the NodeJS event loop model

Better understand the NodeJS event loop model

In this article we will try to understand the NodeJS event loop model. The Node.js event loop is a fundamental aspect of how Node.js operates. It is responsible for handling events, executing asynchronous tasks, and providing a non-blocking I/O mechanism.

Here’s a diagram that illustrates the event loop model in Node.js:

Event LoopI/O CallbackTimerCallbackCallback

NodeJS event loop model

At the core of the event loop model, we have the event loop itself, which is a continuous loop that listens for events and dispatches them to the appropriate handlers. The event loop consists of several phases, each of which handles a specific type of event.

First phase

Timers phase, which handles setTimeout and setInterval callbacks. These callbacks are executed after a specified delay or at a specific interval.

Second phase

“I/O callbacks” phase, which handles I/O events such as network requests, file system operations, and other asynchronous tasks. When an I/O event occurs, Node.js registers a callback to be executed when the operation is complete.

Third phase

“Idle, prepare” phase, which is used for internal Node.js operations.

Fourth Phase

“Poll” phase is where the event loop spends most of its time. In this phase, the event loop waits for new I/O events to occur or for previously registered callbacks to be executed.

Fifth Phase

Once the poll phase has completed, the event loop moves on to the “check” phase, where any callbacks registered with setImmediate are executed.

Final Phase

The “close callbacks” phase is the final phase of the event loop. In this phase, any callbacks registered with the “close” event are executed.

Below is an example that demonstrates the event loop model in Node.js:

console.log('Start');

setTimeout(() => {
  console.log('Timeout callback');
}, 0);

setImmediate(() => {
  console.log('Immediate callback');
});

fs.readFile('/path/to/file', (err, data) => {
  if (err) {
    throw err;
  }
  console.log('File contents:', data.toString());
});

console.log('End');

In this example, we first log “Start” to the console. We then register a setTimeout callback with a delay of 0 milliseconds, which means it will be executed as soon as possible after the current phase of the event loop completes.

Next, we register an immediate callback using the setImmediate function. This callback will be executed in the “check” phase of the event loop, after the “poll” phase has completed.

We then use the fs.readFile function to read the contents of a file. This function is asynchronous and will not block the event loop while the file is being read. When the file read is complete, the callback function is executed and logs the contents of the file to the console.

Finally, we log “End” to the console. This code demonstrates how Node.js uses the event loop to handle asynchronous operations in a non-blocking manner.

Hope you liked the brief overview of the Node.js event loop model!

Further Readings

NodeJS

How to run NodeJS server as Windows service

Please share