Node.js runs your JavaScript on one thread, yet handles thousands of users. The secret is the event loop.
How it works
- Your code runs on the call stack
- Slow work (files, network, timers) is handed to the system and Node's thread pool
- When that work finishes, its callback is put in a queue
- When the stack is empty, the event loop takes the next callback and runs it
Order of execution
- Synchronous code
- Microtasks:
process.nextTick, then resolved Promises - Timers (
setTimeout,setInterval) - I/O callbacks
setImmediate(check phase)
The golden rule
Don't block the event loop. A long loop, readFileSync, or heavy CPU work (resizing images, big calculations) stops every user's request. Use async functions, streams, or worker threads for heavy CPU tasks.
Example
Example — Guess the output order
JavaScript
console.log('1: start');
setTimeout(() => console.log('5: setTimeout'), 0);
setImmediate(() => console.log('6: setImmediate'));
Promise.resolve().then(() => console.log('4: promise'));
process.nextTick(() => console.log('3: nextTick'));
console.log('2: end');
Output: 1: start, 2: end, 3: nextTick, 4: promise, 5: setTimeout, 6: setImmediate. Sync code runs first, then microtasks, then timers. (setTimeout vs setImmediate order can vary in the main script, but microtasks always come first.)