Handbooks / Node.js / Chapter 2
The Node.js Event Loop
7 pages · ~5 min✓ Reviewed
Builds on Modules and npm. Next up: Core Modules: fs, path, http and os.
Single-Threaded Model and Mental Model
1. One Thread for JS
- JS runs on one main thread: one call stack, one callback at a time
- So no data races on plain JS variables
- Single-threaded for JS only: libuv, the OS kernel and a thread pool do I/O and heavy work
2. Mental Model
- Stackruns sync code
- Backgroundlibuv, kernel, pool
- Queuesfinished callbacks
- Event looppush one at a time
3. I/O-bound vs CPU-bound
libuv and the Event Loop Phases
1. What libuv Is
- libuv = the C library under Node
- Gives Node the event loop, async network I/O and a thread pool
- I/O backends:
epoll(Linux),kqueue(macOS),IOCP(Windows)
2. Phases of One Loop Turn
- timers
- pending callbacks
- idle / prepare
- poll
- check
- close callbacks
nextTick vs setImmediate vs setTimeout
1. Who Runs Where
| API | Runs in | When |
|---|---|---|
process.nextTick | nextTick queue | right after current operation |
Promise.then | microtask queue | after nextTick queue drains |
Blocking the Event Loop
1. What blocking is
- Blocking = one callback runs long synchronously
- Timers, requests, I/O all wait: p99 latency spikes for every client
2. Culprits and fixes
| Culprit | Fix |
|---|
Worker Threads for CPU-Bound Work
1. What a Worker Is
- Separate thread: own V8 isolate, event loop, memory
- Messages are copied by structured clone
- Transfer an ArrayBuffer: moved, not copied
SharedArrayBuffer+Atomics= shared memory
javascript
// main.js const w = new Worker('./job.js', { workerData }); w.on('message', handle); // job.js parentPort.postMessage(heavy(workerData));
workerData in, postMessage out
Node Concurrency Cheat Sheet
1. Loop turn
nextTickand promise microtasks run between callbacks- One turn visits six phases in order
- timers
- pending
- idle/prepare
- pollI/O
- checksetImmediate
- close
2. Priority
Check yourself
A CommonJS file schedules setTimeout(t, 0), setImmediate(i), Promise.resolve().then(p) and process.nextTick(n), then logs s. What prints, in order?
s, thenn, thenp.tandicome after, in no fixed order from the main module.