Chapter 06: libuv & async IO explained the ideas: one thread, blocking vs non-blocking, and libuv doing the waiting. Now you'll see them in real code. For each example, predict the output before reading it. That habit is exactly what interviewers test.
In this chapter you'll learn
- how to read a program and predict the order of its output
- the difference between
readFileSyncandreadFilein practice - how a synchronous function blocks everything, measured in seconds
- why
setTimeout(fn, 0)never runs immediately
Before you start: read Chapter 06: libuv & async IO. All examples are in Code/: sync.js, async.js, blocking.js and setTimeoutZero.js.
The one rule you need
All synchronous code runs first, from top to bottom. Callbacks run only after that, when the call stack is empty.
Asynchronous functions like fs.readFile, https.get and setTimeout don't run your callback. They register it with libuv and return immediately. The callback runs later, once its result is ready and the main code has finished.
Example 1: purely synchronous code
// sync.js
console.log("Synchronous Code");
var a = 62656954;
var b = 6256546;
function multiply(a, b) {
return a * b;
}
var c = multiply(a, b);
console.log("Multiplication of a and b is " + c);// sync.js
console.log("Synchronous Code");
var a = 62656954;
var b = 6256546;
function multiply(a, b) {
return a * b;
}
var c = multiply(a, b);
console.log("Multiplication of a and b is " + c);Output:
Synchronous Code
Multiplication of a and b is 392016114920884Synchronous Code
Multiplication of a and b is 392016114920884Nothing surprising: every line runs in order on the call stack. No libuv involved.
Example 2: mixing sync and async
The examples in this chapter use ES Modules (import), the modern standard. To run them, add "type": "module" to your package.json or name the files .mjs. The CommonJS form is const fs = require("node:fs"); see the CommonJS → ES Modules cheat sheet. (The course's own files in Code/ use CommonJS; the behaviour is the same.)
// async.js (simplified)
import fs from "node:fs";
import https from "node:https";
console.log("1. start");
fs.readFileSync("./file.txt", "utf8"); // sync: blocks until the file is read
console.log("2. after readFileSync");
https.get("https://dummyjson.com/products/1", (res) => {
console.log("5?. data fetched"); // async: network
});
setTimeout(() => {
console.log("6?. after 5 seconds"); // async: timer
}, 5000);
fs.readFile("./file.txt", "utf-8", (err, data) => {
console.log("4?. file data: " + data); // async: file system
});
const c = 5 * 10;
console.log("3. multiplication: " + c);// async.js (simplified)
import fs from "node:fs";
import https from "node:https";
console.log("1. start");
fs.readFileSync("./file.txt", "utf8"); // sync: blocks until the file is read
console.log("2. after readFileSync");
https.get("https://dummyjson.com/products/1", (res) => {
console.log("5?. data fetched"); // async: network
});
setTimeout(() => {
console.log("6?. after 5 seconds"); // async: timer
}, 5000);
fs.readFile("./file.txt", "utf-8", (err, data) => {
console.log("4?. file data: " + data); // async: file system
});
const c = 5 * 10;
console.log("3. multiplication: " + c);Typical output:
1. start
2. after readFileSync
3. multiplication: 50
4?. file data: ... ← usually first: a small local file reads fast
5?. data fetched ← a network round trip takes longer
6?. after 5 seconds ← the timer can't fire before 5 seconds1. start
2. after readFileSync
3. multiplication: 50
4?. file data: ... ← usually first: a small local file reads fast
5?. data fetched ← a network round trip takes longer
6?. after 5 seconds ← the timer can't fire before 5 secondsRead the order like this:
- Lines 1, 2 and 3 are synchronous, so they always come first and in order.
- The three callbacks (4, 5, 6) run later, in the order their results become ready. That's why they're marked with
?: a slow disk or a fast network could swap 4 and 5. Only the 5-second timer is guaranteed to be last here.
Who handles what:
fs.readFile→ libuv's thread pool reads the filehttps.get→ the operating system watches the network socket (no thread pool)setTimeout→ libuv's timers
Chapter 10: Thread Pool in libuv explains the thread pool vs OS difference in detail.
readFileSync with a callback does nothing useful
A common beginner mistake:
// ❌ Wrong: readFileSync does not take a callback
fs.readFileSync("./file.txt", "utf-8", (err, data) => {
console.log(data); // never runs
});// ❌ Wrong: readFileSync does not take a callback
fs.readFileSync("./file.txt", "utf-8", (err, data) => {
console.log(data); // never runs
});readFileSync returns the data. Extra arguments are ignored, so the callback never runs and the data is thrown away. The correct sync version:
// ✅ Sync: the result is the return value, errors are thrown
try {
const data = fs.readFileSync("./file.txt", "utf-8");
console.log(data);
} catch (err) {
console.error("Could not read file:", err.message);
}// ✅ Sync: the result is the return value, errors are thrown
try {
const data = fs.readFileSync("./file.txt", "utf-8");
console.log(data);
} catch (err) {
console.error("Could not read file:", err.message);
}And the correct async versions:
// ✅ Async with a callback: errors come as the FIRST argument
fs.readFile("./file.txt", "utf-8", (err, data) => {
if (err) return console.error(err.message);
console.log(data);
});
// ✅ Async with Promises / async-await (what modern code usually uses)
import { readFile } from "node:fs/promises"; // imports are hoisted: normally you write them at the top
const text = await readFile("./file.txt", "utf-8"); // top-level await: allowed in ES Modules
console.log(text);
// (In CommonJS, top-level await is a SyntaxError: wrap it in an async function main() {} and call main().)// ✅ Async with a callback: errors come as the FIRST argument
fs.readFile("./file.txt", "utf-8", (err, data) => {
if (err) return console.error(err.message);
console.log(data);
});
// ✅ Async with Promises / async-await (what modern code usually uses)
import { readFile } from "node:fs/promises"; // imports are hoisted: normally you write them at the top
const text = await readFile("./file.txt", "utf-8"); // top-level await: allowed in ES Modules
console.log(text);
// (In CommonJS, top-level await is a SyntaxError: wrap it in an async function main() {} and call main().)Node.js callbacks follow the error-first convention: (err, result) => {}. Always check err before using result.
Example 3: watching the main thread get blocked
crypto.pbkdf2 derives a key from a password. It's deliberately slow (that's what makes it secure; more in Chapter S2 09: Encrypting Passwords). Node.js has both versions:
// blocking.js
import crypto from "node:crypto";
console.log("Program started");
// SYNC: blocks the main thread. 5,000,000 iterations takes seconds.
crypto.pbkdf2Sync("akshumint999", "salt", 5000000, 20, "sha512");
console.log("First synchronous key is generated");
// ASYNC: runs on a libuv thread-pool thread; the callback runs later
crypto.pbkdf2("akshumint999", "salt", 50000, 20, "sha512", (err, key) => {
console.log("Asynchronous key:", key);
});
function addition(x, y) {
return x + y;
}
console.log("Addition is: " + addition(5, 10));// blocking.js
import crypto from "node:crypto";
console.log("Program started");
// SYNC: blocks the main thread. 5,000,000 iterations takes seconds.
crypto.pbkdf2Sync("akshumint999", "salt", 5000000, 20, "sha512");
console.log("First synchronous key is generated");
// ASYNC: runs on a libuv thread-pool thread; the callback runs later
crypto.pbkdf2("akshumint999", "salt", 50000, 20, "sha512", (err, key) => {
console.log("Asynchronous key:", key);
});
function addition(x, y) {
return x + y;
}
console.log("Addition is: " + addition(5, 10));Output (measured on a laptop, the whole run took about 4 seconds):
Program started
← ~4 second pause: pbkdf2Sync blocks EVERYTHING
First synchronous key is generated
Addition is: 15 ← runs right away: pbkdf2 (async) didn't block
Asynchronous key: <Buffer 63 de 36 ...>Program started
← ~4 second pause: pbkdf2Sync blocks EVERYTHING
First synchronous key is generated
Addition is: 15 ← runs right away: pbkdf2 (async) didn't block
Asynchronous key: <Buffer 63 de 36 ...>During those 4 seconds, the single thread can do nothing else. In a web server, every other user's request would be frozen. That's why *Sync functions don't belong in request handlers.
Sync functions in Node.js have no callback: they return the result or throw an error. If you see a callback on a *Sync function, it's a bug.
Example 4: setTimeout(fn, 0)
// setTimeoutZero.js
console.log("SetTimeoutZero demonstration");
var a = 5;
var b = 10;
setTimeout(() => {
console.log("SetTimeout function after 3 seconds");
}, 3000);
setTimeout(() => {
console.log("Call me asap");
}, 0);
function multiply(x, y) {
return x * y;
}
console.log("Multiplication answer is : " + multiply(a, b));// setTimeoutZero.js
console.log("SetTimeoutZero demonstration");
var a = 5;
var b = 10;
setTimeout(() => {
console.log("SetTimeout function after 3 seconds");
}, 3000);
setTimeout(() => {
console.log("Call me asap");
}, 0);
function multiply(x, y) {
return x * y;
}
console.log("Multiplication answer is : " + multiply(a, b));Output:
SetTimeoutZero demonstration
Multiplication answer is : 50
Call me asap
SetTimeout function after 3 secondsSetTimeoutZero demonstration
Multiplication answer is : 50
Call me asap
SetTimeout function after 3 secondsWhy does "Call me asap" come after the multiplication, even with a delay of 0?
setTimeoutnever runs its callback directly. It registers a timer with libuv and returns.- A delay of
0is treated as 1 millisecond. It means "as soon as possible after the current code", not "right now". - The callback can only run when the call stack is empty (all synchronous code finished) and the event loop reaches its timers phase.
The delay is a minimum, not a promise. If your synchronous code takes 2 seconds, a setTimeout(fn, 0) waits 2 seconds. Some other callbacks can also run before it: process.nextTick callbacks and resolved Promises always run first. Chapter 09: libuv & event loop explains this order exactly.
Practice: predict the output
console.log("A");
setTimeout(() => console.log("B"), 0);
setTimeout(() => console.log("C"), 10);
console.log("D");
for (let i = 0; i < 1e8; i++) {} // a slow loop, ~100 ms
console.log("E");console.log("A");
setTimeout(() => console.log("B"), 0);
setTimeout(() => console.log("C"), 10);
console.log("D");
for (let i = 0; i < 1e8; i++) {} // a slow loop, ~100 ms
console.log("E");Answer
A
D
E
B
CA
D
E
B
CA, D and E are synchronous, so they print first. The slow loop delays both timers, but neither callback can interrupt it. Afterwards, both timers have expired; B (1 ms) was registered with an earlier deadline than C (10 ms), so it runs first.
Key takeaways
- All synchronous code runs first. Callbacks run only after the call stack is empty.
- Async callbacks run in the order their results become ready, which you often can't predict exactly.
readFileSyncreturns data and throws errors; it never takes a callback.- Node.js callbacks are error-first:
(err, result). - A
*Syncfunction blocks the whole process, which freezes every user of a server. setTimeout(fn, 0)means "after the current code, in the timers phase", with a minimum of 1 ms.
Interview questions
Q1. What is the output order of console.log, setTimeout(0) and a resolved Promise?
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");Output: 1, 4, 3, 2. Synchronous logs first (1, 4). Then the microtask queue (Promise callbacks) is emptied before the event loop moves on, so 3 comes before the timer callback 2. See Chapter 09: libuv & event loop.
Q2. What is the difference between fs.readFile and fs.readFileSync?
readFileSync blocks the thread until the file is read, then returns the content (and throws on error). readFile starts the read on libuv's thread pool, returns immediately, and delivers the content to an error-first callback later. In servers, use readFile or fs.promises.readFile so other requests aren't blocked.
Q3. Does setTimeout(fn, 0) run immediately?
No. It schedules fn to run in the event loop's timers phase after at least 1 ms, and only once the call stack is empty. All remaining synchronous code, process.nextTick callbacks and Promise callbacks run before it.
Q4. What is an error-first callback?
It's the Node.js convention where a callback's first parameter is an error (or null if everything went fine) and the following parameters are the results: (err, data) => {}. It forces you to think about the error case, and lets errors be passed along without throwing across async boundaries.
Q5. Why are synchronous functions dangerous in a Node.js server?
All requests share one JavaScript thread. A synchronous call (readFileSync, pbkdf2Sync, a huge JSON.parse, a long loop) occupies that thread until it finishes, so every other request waits. The server looks frozen. They're fine at startup (reading a config file once) but not inside request handlers.
Q6. What is "callback hell", and how do you avoid it?
It's deeply nested callbacks (callback inside callback inside callback), which are hard to read and handle errors in. Avoid it with Promises and async/await (await fsp.readFile(...)), by splitting code into small named functions, and with util.promisify for old callback-style APIs.
What's next
You've seen V8 run synchronous code and libuv handle the async parts. Before diving into the event loop, Chapter 08: Deep dive into v8 JS Engine goes inside V8 itself: how your code is parsed, interpreted, optimized, and how memory is cleaned up.