Node.js Reference ยท Concepts and Pitfalls
Sync versus async APIs in Node.js
Why Node.js offers both synchronous and asynchronous APIs, how sync calls block the event loop, and when a synchronous call is the right choice.
Many Node.js modules offer the same operation in several forms: a callback version (fs.readFile), a promise version (fs.promises.readFile) and a synchronous version (fs.readFileSync). The difference is not the result but what happens to the single thread that runs your JavaScript while the operation is under way.
An asynchronous call starts the work, returns immediately, and lets the event loop run other things (timers, other requests) until the result is ready. A synchronous call holds the thread until it finishes: nothing else in your process runs, including incoming requests, timers and I/O callbacks. That is cheap when the thread has nothing else to do and costly in a server under load.
const text = fs.readFileSync('config.json', 'utf8'); // blocks const text2 = await fs.promises.readFile('config.json', 'utf8'); // does not
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
When synchronous is fine
- Startup code. Reading configuration, loading certificates or reading a template before the server starts is a one-time cost, and no requests are waiting yet.
- Command-line scripts and build tools. A script that does one thing after another gains nothing from asynchrony, and the code is shorter and easier to follow.
- Tests and fixtures, where simplicity matters and nothing else shares the thread.
- Tiny, fast operations such as
fs.existsSync()on a local path, orpathandurlhelpers, which are synchronous by nature. require()itself is synchronous, which is why CommonJS code loads modules at startup, and whyawait import()in a request handler is slower on the first call.
When it hurts
- Request handlers. One
readFileSyncof a slow disk (or a network drive) in a handler stalls every concurrent request for its whole duration. - Big data and CPU work:
zlib.gzipSync,crypto.pbkdf2Sync,execSyncwith long commands, andJSON.parseof huge strings. For CPU work, use worker threads; for I/O, use the async APIs. - Anything that can wait on the outside world: network file systems, DNS (
dns.lookupuses the thread pool), child processes.
Usage notes
- Naming: sync functions end in
Sync(readFileSync,execSync,randomByteswith no callback is also sync). Functions without that suffix may still be blocking, so check the docs. - Errors: sync functions throw; callbacks receive an error first; promises reject. Use
try/catchfor sync andawait,.catch()for promises. - Async is not parallel.
awaitin a loop runs one operation at a time; usePromise.all()(with a limit) to overlap them. Async file operations run in libuv's thread pool, four threads by default (UV_THREADPOOL_SIZE). - Async has overhead. For a single tiny file at startup, the async form is slower and noisier than the sync one. Do not convert everything on principle.
- Mixing styles is fine as long as you know where the blocking happens. Move sync calls out of the hot path rather than out of the program.
- Measure.
performance.eventLoopUtilization()andmonitorEventLoopDelay()show whether the loop is being blocked.