1. How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).
❓ Context: Explain libuv Event Loop phases, microtask queue priority (process.nextTick, Promises), and non-blocking I/O execution.
Node.js runs single-threaded JavaScript execution backed by libuv for asynchronous I/O. The Event Loop coordinates asynchronous callbacks across 6 distinct phases:
6 Event Loop Phases:
Microtask Queue Priority:
'process.nextTick()' and resolved 'Promises' execute immediately after the current operation finishes, BEFORE the event loop advances to the next phase!
import fs from 'node:fs';
console.log('1. Script Start');
setTimeout(() => console.log('2. setTimeout (Timers Phase)'), 0);
setImmediate(() => console.log('3. setImmediate (Check Phase)'));
process.nextTick(() => console.log('4. process.nextTick (Microtask)'));
Promise.resolve().then(() => console.log('5. Promise.then (Microtask)'));
fs.readFile(__filename, () => {
console.log('6. I/O Callback (Poll Phase)');
});
console.log('7. Script End');Microtasks (process.nextTick and Promises) execute immediately after the current operation completes, before the event loop advances phases.