JavaScript runs on one thread, yet a Node.js server can handle thousands of users at once. How? The answer is a C library called libuv. This chapter explains synchronous vs asynchronous code, and the role libuv plays in making Node.js fast.
In this chapter you'll learn
- what "single-threaded" and "synchronous" really mean
- how JavaScript runs code: the call stack and the memory heap
- the difference between synchronous and asynchronous code
- what libuv is and what it does for Node.js
- when libuv uses the operating system and when it uses its thread pool
Before you start: read Chapter 02: JS on the Server (V8 and how Node.js is built). This chapter is the overview; Chapter 07: sync async, setTimeout Zero - Code shows it in code, Chapter 09: libuv & event loop covers the event loop and Chapter 10: Thread Pool in libuv the thread pool.
JavaScript is single-threaded and synchronous
A thread is a sequence of instructions the CPU works through, one after another. Think of it as one worker.
Single-threaded means JavaScript has one such worker. It can do only one thing at a time.
Synchronous means that worker does tasks in order: line 1, then line 2, then line 3. Each line waits for the previous one to finish.
console.log("A");
const total = 5 + 10;
console.log("B", total);
// Always prints A, then B 15. In that order, every time.console.log("A");
const total = 5 + 10;
console.log("B", total);
// Always prints A, then B 15. In that order, every time.How V8 runs your code: call stack and memory heap
The JavaScript engine (V8) has two main parts you should know about:
- Memory heap: where values are stored: objects, arrays, functions, strings.
- Call stack: a list of the functions currently running. When a function is called, it's pushed on top; when it returns, it's popped off. JavaScript always works on whatever is on top of the stack.
function multiply(a, b) {
return a * b;
}
function square(n) {
return multiply(n, n);
}
console.log(square(4)); // 16function multiply(a, b) {
return a * b;
}
function square(n) {
return multiply(n, n);
}
console.log(square(4)); // 16The stack grows and shrinks like this:
1. [ global ] start of the file
2. [ global, square(4) ] square is called
3. [ global, square(4), multiply(4, 4) ] square calls multiply
4. [ global, square(4) ] multiply returns 16
5. [ global ] square returns 16
6. [ global, console.log(16) ] print it1. [ global ] start of the file
2. [ global, square(4) ] square is called
3. [ global, square(4), multiply(4, 4) ] square calls multiply
4. [ global, square(4) ] multiply returns 16
5. [ global ] square returns 16
6. [ global, console.log(16) ] print itBecause there's only one call stack, if one function takes 5 seconds, nothing else can run for those 5 seconds. That's what "blocking" means.
Synchronous vs asynchronous
A restaurant analogy
Imagine a restaurant with one waiter (the single JavaScript thread).
- Synchronous waiter: takes table 1's order, walks to the kitchen, stands there until the food is cooked, serves it, then goes to table 2. With ten tables, most customers wait a very long time.
- Asynchronous waiter: takes table 1's order, hands it to the kitchen, immediately takes table 2's order, then table 3's... When the kitchen rings the bell ("table 1's food is ready"), the waiter serves it.
The kitchen is libuv and the operating system: the cooking (waiting for disks and networks) happens there, while the waiter keeps working.
In code
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.
import fs from "node:fs";
// SYNCHRONOUS: the thread waits here until the whole file is read
const data = fs.readFileSync("./big-file.txt", "utf-8");
console.log("Read", data.length, "characters");
// ASYNCHRONOUS: start the read, move on, get called back later
fs.readFile("./big-file.txt", "utf-8", (err, data) => {
console.log("Callback: read", data.length, "characters");
});
console.log("This prints BEFORE the callback");import fs from "node:fs";
// SYNCHRONOUS: the thread waits here until the whole file is read
const data = fs.readFileSync("./big-file.txt", "utf-8");
console.log("Read", data.length, "characters");
// ASYNCHRONOUS: start the read, move on, get called back later
fs.readFile("./big-file.txt", "utf-8", (err, data) => {
console.log("Callback: read", data.length, "characters");
});
console.log("This prints BEFORE the callback");| Synchronous | Asynchronous | |
|---|---|---|
| Waits for the result? | yes, the thread is blocked | no, the thread continues |
| Result arrives | as the return value | later, in a callback (or a Promise) |
| Node.js naming | readFileSync, pbkdf2Sync... | readFile, pbkdf2, fs.promises.readFile... |
| Good for | startup scripts, small CLI tools | servers: anything handling many requests |
In a server, prefer the asynchronous versions. One readFileSync on a large file blocks every user of your app until it's done. You'll see this happen in Chapter 07: sync async, setTimeout Zero - Code.
What is libuv?
V8 only knows how to run JavaScript. It has no idea how to read a file, open a network connection or start a timer. Node.js needs something to do that, on every operating system, without blocking the JavaScript thread.
That something is libuv: an open-source C library for asynchronous I/O. Originally written for Node.js, it's now also used by other projects (Julia, Luvit and more).
libuv gives Node.js:
- the event loop: the mechanism that decides which callback runs next (Chapter 09: libuv & event loop)
- asynchronous network I/O (TCP, UDP, DNS)
- asynchronous file system operations
- timers (
setTimeout,setInterval) - a thread pool for work that can't be done asynchronously by the OS (Chapter 10: Thread Pool in libuv)
- child processes, signals, and more, the same way on Linux, macOS and Windows
How a call travels through Node.js
When your code calls an async function such as fs.readFile:
- V8 runs your JavaScript until it reaches the call.
- Node.js's C++ bindings translate it into a request for libuv.
- libuv starts the operation somewhere else (more on where below), and your JavaScript keeps running.
- When the operation finishes, libuv puts your callback in a queue.
- When the call stack is empty, the event loop takes the callback from the queue and V8 runs it.
Where does the waiting happen?
libuv uses two different strategies, depending on the kind of work:
| Kind of work | How libuv handles it | Thread pool used? |
|---|---|---|
| Network (HTTP, TCP sockets, database connections) | asks the operating system to watch the sockets and tell it when data arrives (epoll on Linux, kqueue on macOS, IOCP on Windows) | No |
| Timers | tracked by the event loop itself | No |
File system (fs.readFile...), dns.lookup, crypto.pbkdf2, zlib | runs the blocking call on one of its worker threads | Yes (4 threads by default) |
So the statement "Node.js is single-threaded" needs care: your JavaScript runs on one thread, but Node.js as a whole uses extra threads behind the scenes. Chapter 10: Thread Pool in libuv goes into the thread pool and epoll in detail.
Concurrency vs parallelism
These two words come up in interviews all the time:
- Concurrency: dealing with many tasks at once by switching between them. One waiter serving ten tables is concurrent.
- Parallelism: doing many tasks at the exact same moment on different CPU cores. Ten waiters serving ten tables is parallel.
Node.js's JavaScript is concurrent but not parallel: it juggles thousands of requests on one thread. The real parallel work (disk reads in the thread pool, the OS handling network packets) happens outside JavaScript.
Common mistakes
- Thinking async code runs "at the same time" as your JavaScript. Your callback still runs on the single thread, but only after the current code finishes and the call stack is empty.
- Using
*Syncfunctions inside request handlers. They block every other request. - Believing everything async uses the thread pool. Network I/O doesn't; it uses the OS's event notification.
- Doing heavy calculations on the main thread (big loops, image processing). Async I/O doesn't help with CPU-bound work. See Chapter 10: Thread Pool in libuv for what to do instead.
Key takeaways
- JavaScript runs on one thread with one call stack: one thing at a time, in order.
- Synchronous code blocks until it finishes. Asynchronous code starts the work and continues; a callback runs later.
- libuv is the C library that gives Node.js the event loop, async I/O and a thread pool.
- Network I/O uses the OS's event notification (epoll/kqueue/IOCP), not the thread pool.
- File system,
dns.lookup, crypto and zlib use the thread pool (4 threads by default). - Node.js is concurrent (many tasks in progress) without running your JavaScript in parallel.
Interview questions
Q1. What is libuv and why does Node.js need it?
libuv is a cross-platform C library for asynchronous I/O. V8 can only run JavaScript; libuv gives Node.js the event loop, non-blocking network and file operations, timers, and a thread pool, all working the same way on Linux, macOS and Windows. Without libuv, Node.js couldn't do I/O without blocking its single JavaScript thread.
Q2. If JavaScript is single-threaded, how does Node.js handle many requests at once?
The JavaScript thread never waits for I/O. It starts an operation, hands it to libuv, and moves on to the next request. The OS (for network I/O) or libuv's thread pool (for files, crypto) does the waiting. When results are ready, their callbacks are queued and the event loop runs them one by one. So many requests are in progress at once, while only one piece of JavaScript runs at any moment.
Q3. What is the difference between synchronous and asynchronous code?
Synchronous code runs step by step and each step waits for the previous one; a slow operation blocks the thread. Asynchronous code starts a slow operation and continues immediately; the result is delivered later through a callback, a Promise or async/await.
Q4. What is the call stack?
The call stack is the structure V8 uses to track which function is currently running. Calling a function pushes a frame onto the stack, and returning pops it off. JavaScript has a single call stack, so only one function runs at a time. If it never empties (infinite recursion), you get RangeError: Maximum call stack size exceeded.
Q5. Does every asynchronous operation in Node.js use the thread pool?
No. Network operations use the operating system's async notification (epoll, kqueue, IOCP), and timers are handled by the event loop: neither uses the pool. The thread pool is used for file system calls, dns.lookup, some crypto functions (pbkdf2, scrypt, randomBytes) and zlib compression.
Q6. What's the difference between concurrency and parallelism?
Concurrency is having many tasks in progress and switching between them; parallelism is executing several tasks at the same instant on different cores. Node.js's JavaScript is concurrent (one thread juggling many requests); parallelism happens in the OS and libuv's thread pool, or explicitly with worker threads or the cluster module.
What's next
Let's see all of this in real code. In Chapter 07: sync async, setTimeout Zero - Code you'll run synchronous and asynchronous examples side by side, predict their output, and discover why setTimeout(fn, 0) doesn't run immediately.