skip to content

In Node.js, how do you choose between the node:fs/promises, callback and Sync forms of a file operation, and when is a Sync call acceptable?

level: juniorimportance: must knowfreq 68%

answer

  1. three forms of one operation
  2. who waits: the thread or a callback
  3. threadpool behind the async forms
  4. startup and CLIs tolerate blocking

basics

~20 s

Node's fs offers its file operations in promise, callback and Sync forms. Default to node:fs/promises with await, keep callbacks for measured hot paths, and confine Sync calls to startup code and CLIs, because they block the event loop.

solid answer

~40 s

All three forms do the same system call; they differ in who waits. The promise form (`node:fs/promises`) and the callback form hand the work to libuv's threadpool and let the event loop keep serving other requests; the promise form reads best with `await` and `try/catch`, and the docs say the callback form is the one to prefer when maximal performance in time and memory is required. A Sync form such as `readFileSync` runs on the main thread and blocks the event loop until the disk answers, so every other request waits. That is fine where nothing else is waiting: reading config once before `server.listen()`, a build script, a CLI. It is never fine inside a request handler, however small the file.

code

javascript · 17 lines
javascript
import { readFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';

// Startup: nothing else is running yet, so blocking is harmless.
const config = JSON.parse(readFileSync(new URL('./config.json', import.meta.url), 'utf8'));

createServer(async (req, res) => {
  try {
    // Request time: never block the event loop.
    const body = await readFile(new URL('./banner.txt', import.meta.url), 'utf8');
    res.end(body);
  } catch (err) {
    res.statusCode = err.code === 'ENOENT' ? 404 : 500;
    res.end();
  }
}).listen(config.port);

go deeper

for a junior

Recall the three forms, how each reports errors, and the one rule: Sync calls block the event loop, so they belong at startup and in CLIs only.

for a middle

Explain that the promise and callback forms both run on libuv's threadpool, why that pool can still become a bottleneck, and why concurrent writes to one file need serialising.

for a senior

Show the judgment: spot a Sync call hiding in request-time code, explain why disk latency rather than file size sets its cost, and bound file concurrency under load.

for a principal

Frame it as a team default: fs/promises everywhere, callbacks only where a profile justifies them, and a lint or review rule that keeps Sync calls out of request paths.

## Three forms of the same operation Almost every operation in Node's `node:fs` module comes in three shapes (a few, such as `fs.watch`, have no Sync form). They reach the same operating-system call; the difference is **who waits for it** and **how errors arrive**. | Form | Import | How it reports | Where the work runs | |---|---|---|---| | Promise | `import { readFile } from 'node:fs/promises'` | returns a promise; rejects on error | libuv's threadpool | | Callback | `import { readFile } from 'node:fs'` | calls `(err, result)` last | libuv's threadpool | | Sync | `import { readFileSync } from 'node:fs'` | returns the value; **throws** on error | the main JavaScript thread | The **event loop** is the single thread that runs your JavaScript and dispatches every callback, timer and incoming request. Anything that occupies that thread delays everything else in the process. ## What the async forms actually do Both the callback API and the promise API hand the file operation to **libuv's threadpool**, a small set of background threads (four unless `UV_THREADPOOL_SIZE` says otherwise). The event loop carries on; when the thread finishes, the callback runs or the promise settles. - The two async forms differ in ergonomics more than in mechanism. `fs/promises` composes with `await`, `Promise.all` and `try/catch`; the callback form costs a little less per call, which is why the fs documentation recommends it when maximal performance is required. - Neither form serialises access. The docs warn that these operations are **not synchronized or threadsafe**: two concurrent writes to the same file can interleave and corrupt it, so serialise writes per file yourself. - "Off the main thread" does not mean free. The threadpool is shared with `dns.lookup`, `crypto` and `zlib`, so a burst of large reads can queue behind other work. How that pool is scheduled is covered with the event loop's phases. - Whole-file reads are deliberately polite. The docs describe `fs.readFile()` reading one chunk at a time (512 KiB per read for a regular file, 64 KiB when the size is unknown) so the event loop turns between chunks; that makes a single read slower, and the docs point to `fs.read()` when raw speed matters. Large files belong in a stream instead, which the streams material covers. ## What a Sync call costs a server A Sync form does the system call on the main thread. While it waits for the disk: - no other request is parsed or answered, - no timer fires and no promise callback runs, - the latency of every request in flight grows by the duration of the call. The duration depends on the disk, the page cache and the file system, not only on the file size. A small file on a network mount or a cold cache can take far longer than it did on a laptop. Measuring that delay is covered with event-loop blocking; the point here is choosing the right form in the first place. ## When a Sync call is the right call Blocking is only harmful when something else is waiting. Sync forms are reasonable when: 1. **Startup, before the server listens.** Reading a config file or a TLS certificate before `server.listen()` blocks nobody, and failing fast with a thrown error is what you want. 2. **Command-line tools and build scripts.** A CLI that does one thing at a time gains nothing from async plumbing; `readdirSync` and `writeFileSync` keep the code linear. 3. **Places where async work cannot finish**, such as a `process.on('exit')` listener, which the process documentation says must only perform synchronous operations. They are wrong in request handlers, message consumers, timers and anything else that runs while the service is taking traffic. Even the startup exception is a convenience rather than a necessity. In an ES module, top-level `await` lets `const config = JSON.parse(await readFile(file, 'utf8'))` read as linearly as the Sync form, so many teams simply use `fs/promises` everywhere and never have to argue about where the line falls. ## Errors in each form - **Promise:** the promise rejects with an `Error` carrying `code` (`'ENOENT'`, `'EACCES'`); catch it with `try/catch` around `await`. - **Callback:** the first argument is the error, `null` or `undefined` on success; an unchecked `err` is silently ignored. - **Sync:** the call throws; an uncaught throw in a handler propagates like any exception. Wrapping `readFileSync` in an `async` function changes none of this: the function still runs the blocking call on the main thread before its promise settles. ## Picking in practice 1. Write new service code against `node:fs/promises` with `await`. 2. Keep the callback form for a hot path you have profiled, or for code already written in that style. 3. Use Sync forms at startup and in CLIs, and make a Sync call inside request-time code a review blocker. 4. When reading many files, bound the concurrency so a burst does not monopolise the threadpool.

  • Is the callback form of node:fs faster than node:fs/promises, and should that change your default?
    Slightly. The fs documentation says the callback APIs are preferable when maximal performance, in both execution time and memory allocation, is required, because they skip promise allocation. Both run on the same threadpool, so the disk dominates. Default to `fs/promises` for readability and reach for callbacks only on a hot path a profile has pointed at.
  • If fs/promises never blocks the event loop, can a burst of readFile calls still slow a Node server down?
    Yes. Every async fs call takes a threadpool thread, four by default, shared with `dns.lookup`, `crypto` and `zlib`. A thousand concurrent `readFile` calls queue there and delay unrelated work, and each one holds the whole file in memory. Bound the concurrency, or stream large files.

  • fs/promises runs the file I/O on the main thread, just later
  • The callback and promise forms use different I/O mechanisms underneath
  • Wrapping readFileSync in an async function makes it non-blocking
  • A Sync call in a request handler is harmless when the file is small
  • Sync forms report failure through a returned error value instead of throwing