Explain it simply
Explain it simply
Picture a restaurant with a single waiter. The waiter takes an order, passes it to the kitchen and moves on to the next table instead of standing at the stove. When a dish is ready, the kitchen calls and the waiter serves it.
In Node.js the waiter is the main thread running your JavaScript, and the kitchen is the operating system doing file and network work. If the waiter starts cooking personally (heavy CPU work), every table waits.
Problem → Why → Solution
The problem: one request makes every other request wait
The server below reads a large CSV file with readFileSync on every request and counts its lines. Tested locally by one person, it feels fast. When 100 users arrive together, each request queues behind the previous one, and even an unrelated /health route stops answering.
import { createServer } from "node:http";
import { readFileSync } from "node:fs";
createServer((req, res) => {
// Blocks the only JavaScript thread until the disk answers
const report = readFileSync("big-report.csv", "utf8");
// Blocks it again while counting characters one by one
let lines = 0;
for (const ch of report) if (ch === "\n") lines++;
res.end(`lines: ${lines}`);
}).listen(3000);Why does it get slow?
Node runs your JavaScript on one main thread. While that thread is stuck in readFileSync or a long loop, it cannot accept new requests, fire timers or call any other callback. With a non-blocking API, the thread stays free while the disk does its work.
Core concept: V8, the event loop and non-blocking I/O
Node divides the work. V8 compiles your JavaScript to machine code and runs it on the call stack: calling a function pushes it onto the stack, and returning pops it off. A C library called libuv owns the event loop and the I/O. For network sockets it uses the operating system's asynchronous notifications; for file system, crypto and zlib work it uses a small background thread pool.
When you call readFile(), Node starts the read and immediately hands back a Promise, so your code keeps running. When the read finishes, the result waits in a queue, and once the call stack is empty the event loop calls your callback. This is non-blocking I/O. Your JavaScript runs on one thread, but Node as a whole uses threads behind the scenes.
Remember the order. First, all the current synchronous code runs to the end. Second, the microtasks run: promise .then callbacks, code after an await, and process.nextTick callbacks. Third, the event loop calls ready timer and I/O callbacks one at a time, draining microtasks again after each one.
So setTimeout(fn, 0) does not mean "now"; it means "as soon as the current work is done". CPU-heavy work, such as resizing big images or crunching large data sets, still blocks the loop and belongs in a worker thread, which the Advanced chapter covers.
You can tell from the name whether a Node API blocks. The fs module offers three ways to read a file: readFileSync, ending in Sync, holds the thread and returns the result directly; the callback-style readFile delivers the result to your function later; and readFile from node:fs/promises returns a Promise you can await. This course uses the promise style by default.
| Style | Example | Blocks the thread? |
|---|---|---|
| Synchronous | readFileSync(path, "utf8") | Yes, nothing else runs until it ends |
| Callback | readFile(path, "utf8", (err, text) => {}) | No |
| Promise | await readFile(path, "utf8") | No |
One main thread, work handed off to the OS
------------------------------------------
your JavaScript (main thread) operating system / libuv
+-----------------------------+ +------------------------+
| readFile("a.txt") ---------------> | read a.txt (background)|
| console.log("next line") | | |
| ...stack becomes empty... | | ...done |
+-----------------------------+ +-----------+------------+
^ |
| event loop: "a.txt is ready"|
+------------ callback queue <-------+- Run all synchronous code
- Start I/O, register callbacks
- Run microtasks (promise callbacks)
- Event loop calls ready callbacks
No callback runs until the call stack is empty.
General pattern: a non-blocking call
import { operation } from "node:module/promises";
operation(args).then((result) => {
// runs later, after the OS has finished the work
});
// code here runs immediately, without waitingA non-blocking function starts the work and returns a Promise right away. Code inside .then() (or after await) runs once the result exists, while the lines below the call keep running without waiting.
Example: spot the runtime and watch Node not wait for the disk
This script checks two host objects, then asks Node to read the script's own file. Watch line 3 appear before line 4: the script reaches its last line before the read has finished.
// intro.mjs - run it with: node intro.mjs
import { readFile } from "node:fs/promises";
console.log("1. Is there a window object?", typeof window !== "undefined");
console.log("2. Is there a process object?", typeof process !== "undefined");
// Ask the OS to read this very file. Node starts the read and moves on.
readFile(new URL(import.meta.url), "utf8").then((source) => {
console.log("4. Read finished, first line:", source.split("\n")[0]);
});
console.log("3. Last line of the script (nothing waited for the disk)");Code breakdown
- Line 2
import { readFile } from "node:fs/promises";node:fs/promises is the promise-returning version of the file functions. The node: prefix marks it as a module built into Node.
- Lines 4-5
typeof process !== "undefined"In a browser, window would be true and process false; Node is the reverse. It is a quick way to tell which runtime your code is in.
- Line 8
readFile(new URL(import.meta.url), "utf8").then((source) => {import.meta.url is this module's file:// URL. readFile hands the read to the OS and returns a Promise at once; the code inside .then runs later.
- Line 12
console.log("3. Last line of the script (nothing waited for the disk)");This line is synchronous, so it runs immediately without waiting for the read. That is why "3." always prints before "4.".
1. Is there a window object? false
2. Is there a process object? true
3. Last line of the script (nothing waited for the disk)
4. Read finished, first line: // intro.mjs - run it with: node intro.mjsMicrotasks versus timers: which runs first?
Promise callbacks go into the microtask queue, while timers wait for the event loop's timer phase. That is why even a timer with a 0 ms delay runs after a promise callback. Run the snippet below and compare it with your prediction. Notice that the lines are written in the order C, B, A but print as A, B, C: the source order of scheduling calls says little about when their callbacks run.
setTimeout(() => console.log("C. timer callback (0 ms)"), 0);
Promise.resolve().then(() => console.log("B. promise callback"));
console.log("A. synchronous code");setTimeout versus setImmediate
When the main script schedules both setTimeout(fn, 0) and setImmediate(fn), which runs first can change from run to run depending on the machine. Never write code that relies on that order.
In real projects
Why this matters in real projects
An API server spends most of its time waiting for a database, another service or the disk. Thanks to non-blocking I/O, a single Node process can keep thousands of those waiting requests in flight without one thread per request. That is why Node is popular for I/O-heavy systems such as chat servers, notification services and API gateways.
On the other hand, most "the server suddenly got slow" incidents in production come from code that blocks the event loop: a readFileSync inside a request handler, a JSON.parse of a payload hundreds of megabytes large, or a regular expression with catastrophic backtracking. Monitoring tools measure event loop lag, how long a ready callback waits before it runs, so teams can spot these problems early.
Common mistakes
Common mistakes
1. Expecting an async result immediately
const text = readFile("a.txt", "utf8"); console.log(text); prints Promise { <pending> }, not the file's text. readFile returns a promise of a future result, not the result itself. Use await or .then().
2. Treating setTimeout(fn, 0) as "run now"
A delay of 0 is only a minimum. The callback runs after the synchronous code and the microtasks, and if the main thread is stuck in a long loop it waits until that loop ends.
3. Using Sync APIs inside request handlers
readFileSync, execSync and friends are fine for one-off work such as reading config at startup. Called on every request, they make all users queue behind each other.
Best practices
Best practices
- Default to promise-based APIs such as node:fs/promises in server code, and keep the Sync versions for startup scripts and small CLI tools.
- Keep each callback short; if you must loop over thousands of items, process them in chunks or move the work to a worker thread.
- Express ordering with await, never with carefully tuned timer delays.
- For every new function, ask whether it waits on I/O or burns CPU; the answer tells you which API to pick.
Mini challenge
Mini challenge: predict the order before you run it
Write a script with two synchronous logs, two timers, one promise callback and a 200 ms busy loop. Write down the output order before running it, then compare.
- Two setTimeout calls with delays of 0 ms and 20 ms
- One Promise.resolve().then() callback
- A loop that blocks the main thread for 200 ms between the two synchronous logs
- The 0 ms timer prints whether it had to wait for the busy loop (true/false)
// order.mjs - predict the order before you run it!
const start = Date.now();
// TODO: a 20 ms timer that logs its label
// TODO: a 0 ms timer that logs whether Date.now() - start >= 200
// TODO: a promise callback
// TODO: first synchronous log
// TODO: busy loop until 200 ms have passed (while + Date.now())
// TODO: second synchronous logExpected: The output appears in this order: 1. first synchronous log 2. second synchronous log, after 200 ms of blocking 3. promise callback (microtask) 4. 0 ms timer - did it wait for the busy loop? true 5. 20 ms timer
Show hint
const end = Date.now() + 200; while (Date.now() < end) {} holds the thread for 200 ms. Both timers have expired when the loop ends, so think about which one expired first.
Show solution
// order.mjs - predict the order before you run it!
const start = Date.now();
setTimeout(() => console.log("5. 20 ms timer"), 20);
setTimeout(() => {
const waited = Date.now() - start;
console.log("4. 0 ms timer - did it wait for the busy loop?", waited >= 200);
}, 0);
Promise.resolve().then(() => console.log("3. promise callback (microtask)"));
console.log("1. first synchronous log");
const end = Date.now() + 200;
while (Date.now() < end) {
// busy loop: the only JavaScript thread is stuck here for 200 ms
}
console.log("2. second synchronous log, after 200 ms of blocking");Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- V8 runs your JavaScript; libuv's event loop handles I/O in the background.
- JavaScript runs on one main thread, so blocking it makes everything wait.
- Order: synchronous code, then microtasks (promises), then timer and I/O callbacks.
- Use non-blocking APIs in request handlers and move heavy CPU work to worker threads.
Node.js event loop — Node.js