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:
- Timers โ Execute setTimeout and setInterval callbacks.
- Pending I/O โ Execute callbacks for completed I/O operations.
- Idle/Prepare โ Internal use only.
- Poll โ Retrieve new I/O events; execute I/O-related callbacks.
- Check โ Execute setImmediate callbacks.
- 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.