Understanding the Single Thread
Node.js runs on a single thread, yet it handles thousands of concurrent connections. How? The secret lies in the Event Loop.
The Event Loop Phases
- Timers: Executes
setTimeout()andsetInterval()callbacks. - Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration.
- Idle, Prepare: Internal use only.
- Poll: Retrieves new I/O events; execute related callbacks.
- Check: Executes
setImmediate()callbacks. - Close Callbacks: e.g.,
socket.on('close', ...).
Microtasks vs Macrotasks
Understanding the priority of tasks is key to preventing blocked threads. process.nextTick() and Promises (Microtasks) have higher priority than setTimeout (Macrotasks).
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
process.nextTick(() => console.log('Next Tick'));
console.log('End');
// Output: Start, End, Next Tick, Promise, Timeout
Best Practices
- Don't block the Event Loop with heavy computation.
- Use Worker Threads for CPU-intensive tasks.
- Understand
async/awaitthoroughly to avoid callback hell.