WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Node.js · Basic · question 3 of 100

What is the Node.js event loop and how does it work?

📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

The Node.js event loop is the heart of Node.js’s asynchronous or non-blocking nature. Its primary function is to handle I/O operations, such as reading files or making network requests. The event loop manages these operations in a non-blocking manner, which allows Node.js to execute multiple tasks concurrently without waiting for any blocking operation to complete.

The event loop is powered by the ‘libuv‘ library, a core component of Node.js that provides asynchronous I/O support.

To understand the event loop better, let’s break down the process into several steps:

1. **Initialization**: When a Node.js application starts, it initializes various resources and structures needed for its execution. After the initialization stage is complete, the event loop starts processing the tasks queued up for execution.

2. **Loop iteration**: The event loop continuously iterates through the different phases in each iteration cycle. These phases include timers, I/O callbacks, idle/prepare, polling, check callbacks, and close callbacks. Each phase is responsible for executing different types of callbacks and handling various asynchronous operations.

Below is a brief description of each phase of the event loop cycle:

- Timers: This phase deals with scheduled callbacks of ‘setTimeout()‘ and ‘setInterval()‘. Callbacks are executed if the timer has reached or passed the specified time duration.

- I/O callbacks: This phase is responsible for executing almost all the callbacks for I/O-related operations, such as TCP and UDP server callbacks.

- Idle/Prepare: This is an internal phase in which libuv performs operations to prepare for the upcoming tick.

- Poll: The poll phase retrieves new I/O events and executes the callbacks corresponding to those events. The event loop waits in this phase for I/O operations to be completed or new tasks to be queued.

- Check: The callbacks registered using ‘setImmediate()‘ are executed in this phase after the polling phase has completed.

- Close callbacks: Some cleanup tasks, such as closing streams and sockets, are executed in this phase.

3. **Task execution**: During each iteration cycle, the event loop checks if there are any pending callbacks or tasks to be performed. If there are tasks to be executed, the event loop picks them up and calls their respective callback functions. These tasks are usually asynchronous and can include reading/writing files and making network requests.

4. **Exit**: If the event loop has no more tasks to be executed and no pending callbacks, the application exits, and the loop terminates.

Here’s a simple example to demonstrate the Node.js event loop:

// example.js
const fs = require('fs');

console.log('Start');

setTimeout(() => {
  console.log('Timer 1') 
}, 0);

fs.readFile('./example.js', () => {
  console.log('File read');
});

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

console.log('End');

In this example, we have a few callbacks using different types of async operations such as ‘setTimeout()‘, ‘fs.readFile()‘, and ‘setImmediate()‘. When we run this code, the output will likely be:

Start
End
Timer 1
Immediate
File read

This output demonstrates that the event loop processes the callbacks in the order dictated by the phases. It executes the synchronous console logs first, moves to the timer phase and runs the timer callback, executes the immediate callback in the check phase, and finally executes the I/O callback after reading the file.

In summary, the Node.js event loop is the mechanism that makes Node.js capable of handling concurrent I/O operations in a non-blocking manner. It continuously processes various types of callbacks to manage asynchronous tasks without blocking the server, resulting in efficient handling of incoming requests and better overall application performance.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Node.js interview — then scores it.
📞 Practice Node.js — free 15 min
📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

All 100 Node.js questions · All topics