Single-threaded JavaScript and nonblocking I/O in Node.js
🎯 Introduction
By the end of this article, you will be able to identify tasks that block other requests and explain how Node.js handles other work while waiting.
🧱 Single-threaded describes JavaScript execution
A thread is a unit of execution within a program. A typical Node.js execution environment runs JavaScript on one main thread. Until the current function finishes, another piece of JavaScript cannot arbitrarily interrupt it and execute simultaneously on that thread.
This does not mean Node.js as a whole can do only one thing. The runtime and operating system can handle disk reads and waiting for network data while the main thread executes other ready code.
I/O means input and output. Reading a file is input; sending content over a network is output. Nonblocking I/O means that after starting an operation, the main thread does not have to wait in place for it to finish.
🛠 Follow a file read through execution
Create a UTF-8 note.txt containing hello. Save the following as non-blocking.mjs and run node non-blocking.mjs:
import { readFile } from 'node:fs'
console.log('Starting read')
readFile('note.txt', 'utf8', (error, text) => {
if (error) {
console.error(error.code)
process.exitCode = 1
return
}
console.log(`Read complete: ${text}`)
})
console.log('Continuing other work')
On success, the output is:
Starting read
Continuing other work
Read complete: hello
First, the program prints “Starting read” and submits the read task. It then continues to the next synchronous log without waiting for the file. Only after reading finishes and the main thread gets an opportunity does the read callback execute.
The callback's first parameter, error, reports failure and is null on success. The second, text, contains the file contents. A missing file reports ENOENT; the example sets a failure exit code and returns without using text. A synchronous try/catch around readFile cannot catch errors delivered through this callback.
🧰 Who reads the file while the main thread continues?
The underlying work for most asynchronous file operations runs in Node.js's internal libuv thread pool. libuv is a low-level library used by Node.js. A thread pool is a reusable group of worker threads that accept tasks, execute them, and move on to the next task.
For the readFile example, responsibilities are divided as follows:
| Step | Executor | What happens |
|---|---|---|
| Call readFile | JavaScript main thread | Submits the file read task |
| Perform underlying file operations | Worker thread in the pool | Performs the required file operations while the main thread can print “Continuing other work” |
| Handle the read result | JavaScript main thread | Runs the callback when scheduled and prints “Read complete: hello” |
Thus, “single-threaded” refers to the main thread executing JavaScript here, not to Node.js having only one internal thread. The readFile callback does not move into the thread pool. JavaScript processing the file contents still occupies the main thread.
Why asynchronous reads can still take a long time
The pool has a limited number of worker threads. If all are busy, newly submitted underlying tasks queue until a worker becomes available. The main thread can continue, but that does not make the file result arrive earlier.
This explains two points: asynchronous APIs avoid making the main thread wait for a file, but do not guarantee immediate completion; submitting more reads does not mean the disk can finish more work simultaneously. Disk load or a busy main thread can also cause delays, so slow reads alone do not prove the pool is too small.
What this means for everyday code
Node.js arranges thread-pool work automatically when you call readFile or fs/promises. You do not need to create threads manually. Remember: file operations can progress in the background, but expensive computation in callbacks still affects other JavaScript.
Not every asynchronous API uses the thread pool. Ordinary network transfers generally rely on operating system nonblocking networking, while timers are scheduled through the event loop.
🧩 Concurrency: tasks make progress over the same period
Concurrency means multiple tasks make progress over the same period. It does not mean the main thread executes multiple pieces of JavaScript at the same instant.
Suppose request A is waiting for a file and request B arrives. With an asynchronous read, the main thread can handle B, then return to finish A when its file result is ready. Their waiting periods can overlap.
Think of a restaurant server handing an order to the kitchen before serving the next customer. The server is not speaking two sentences simultaneously, but several orders are at different stages. This analogy only separates waiting from processing; it does not imply allocating a new thread to every I/O operation.
🪤 Nonblocking I/O does not offload expensive computation
If A's callback runs a long loop, the main thread stays busy with it and B's JavaScript must wait. Computation occupying a thread differs from yielding execution while waiting for I/O.
Likewise, readFileSync still blocks inside an async function. Adding async to a function containing a large loop does not move the loop to another thread.
For programs handling ongoing requests, prefer asynchronous I/O and avoid lengthy computation in callbacks. Memory, disks, and external services also limit concurrency; task counts cannot grow indefinitely.
❓ Questions and answers
Q1: Why does a large loop still cause delays inside an async function?
The current JavaScript thread still executes it. async does not allocate a thread automatically.
Q2: Must other requests wait while one request waits for a file?
Asynchronous file APIs allow other ready tasks to run. Synchronous APIs block the current thread.
Q3: Is more concurrency always better?
No. Exceeding available resources causes queuing, timeouts, and memory pressure.
🧪 Exercise
Run the read example, then change the filename to a missing path. Observe the order of the failure callback and synchronous logs.
// Write your code here
🎉 Try these techniques with your own examples!
