Labs ICT
โญ Pro Login

The Event Loop

How Node.js handles thousands of requests at once.

The Event Loop

The event loop is what makes Node.js fast. It is a single thread that handles all incoming requests by processing them in non-blocking chunks. Let me explain how it works.

How the Event Loop Works

When you run node app.js, Node.js starts the event loop. It runs through these phases:

  1. Timers โ€” Execute setTimeout and setInterval callbacks.
  2. Pending I/O โ€” Execute callbacks for completed I/O operations.
  3. Idle/Prepare โ€” Internal use only.
  4. Poll โ€” Retrieve new I/O events; execute I/O-related callbacks.
  5. Check โ€” Execute setImmediate callbacks.
  6. Close callbacks โ€” Execute close event callbacks (e.g., server.on('close')).

Blocking vs Non-Blocking

// BLOCKING - Don't do this
const fs = require("fs");
const data = fs.readFileSync("large-file.txt");  // Blocks everything
console.log(data);

// NON-BLOCKING - Do this instead
const fs = require("fs").promises;

async function readFile() {
  const data = await fs.readFile("large-file.txt");  // Does not block
  console.log(data);
}

Blocking code stops the event loop. No other requests can be processed until the blocking operation finishes.

Try it Yourself โ†’

process.nextTick and setImmediate

// Runs before the next event loop phase
process.nextTick(() => {
  console.log("Next tick");
});

// Runs in the next check phase
setImmediate(() => {
  console.log("Immediate");
});

console.log("Normal");

Critical Rule: Never block the event loop with CPU-intensive work. Use worker_threads or child processes for heavy computation.

๐Ÿงช Quick Quiz

What is the event loop in Node.js?