Node.js fs/promises: Read, Write, Watch, and Atomic File Operations
writeFile truncates before writing, so a crash leaves half a file. The atomic pattern is temp file, fsync, rename; readFile loads everything, so large files need streams.

Quick Summary
node:fs/promises is the promise-based API over the same libuv file operations as node:fs: each call runs off the main thread and resolves when libuv reports completion. It is the default choice for application code, with node:fs sync calls reserved for startup, CLI scripts, and tests where blocking is acceptable.
Two behaviours are worth knowing before using it. writeFile is not atomic: a crash mid-write leaves a truncated file, and a concurrent reader can see a half-written one. And readFile loads the whole file into memory, so a 2 GB log file is an out-of-memory error, not a slow call.
Atomic replacement is a pattern, not a function: write a temporary file in the same directory, fsync it, rename it over the target. Rename within one filesystem is atomic on POSIX; anything across filesystems fails with EXDEV.
Basic Syntax and Core Signatures
import {
readFile, writeFile, appendFile, copyFile, rename, rm, mkdir, rmdir,
readdir, stat, lstat, open, cp, watch, access, constants,
} from 'node:fs/promises';
import { join } from 'node:path';
// Read
const text = await readFile('config.json', 'utf8');
const buf = await readFile('image.png'); // Buffer
const { size, mtime, mode } = await stat('config.json');
const entries = await readdir('.', { withFileTypes: true });
const all = await readdir('.', { recursive: true, withFileTypes: true }); // Node 18.17+
// Write
await writeFile('out.json', JSON.stringify(data, null, 2), { mode: 0o600 });
await writeFile('log.txt', 'line\n', { flag: 'a' }); // append
await appendFile('log.txt', 'line\n');
// Directories and removal
await mkdir('cache/thumbs', { recursive: true }); // idempotent
await rm('tmp', { recursive: true, force: true, maxRetries: 3 });
await cp('src', 'dst', { recursive: true, force: true }); // Node 16.7+
// Handle-based work
const fh = await open('data.bin', 'r');
try {
const { bytesRead, buffer } = await fh.read(Buffer.alloc(1024), 0, 1024, 0);
} finally {
await fh.close();
}
// Watching
const ac = new AbortController();
for await (const { eventType, filename } of watch('src', { recursive: true, signal: ac.signal })) {
console.log(eventType, filename);
}// The atomic replace, in full
import { open, rename, rm } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { randomBytes } from 'node:crypto';
export async function writeFileAtomic(path, data) {
const tmp = join(dirname(path), `.${randomBytes(6).toString('hex')}.tmp`);
const fh = await open(tmp, 'w');
try {
await fh.writeFile(data);
await fh.sync(); // durability: survives a power loss
} finally {
await fh.close();
}
try {
await rename(tmp, path); // atomic within one filesystem
} catch (err) {
await rm(tmp, { force: true });
throw err;
}
}Key Comparison Table
| Function | Atomic | Creates parent dirs | Loads whole file | Use for |
|---|---|---|---|---|
writeFile | No | No (ENOENT) | Yes | Small files, config, JSON |
appendFile | No | No | Yes | Logs, line protocol |
rename | Yes, same filesystem | No | No | Atomic replace, rotation |
copyFile | No, target truncated first | No | Internally streams | Plain copy |
cp | No | No | Streams | Recursive copy |
rm -r -f equivalent | No | N/A | No | Cleanup, temp trees |
| Error code | Meaning | Usual fix |
|---|---|---|
ENOENT | Path or parent directory missing | mkdir(dir, { recursive: true }) first |
EACCES | Permission denied | Fix mode/ownership; check the process user |
EISDIR | Tried to read a directory as a file | readdir instead |
ENOTDIR | A path component is a file | Check each segment |
ENOSPC | Disk full | Clean up; writeFile already truncated the target |
EMFILE | Too many open files | Limit concurrency, close handles |
EXDEV | Rename across filesystems | Copy then delete, or place the temp file beside the target |
EBUSY | Target open elsewhere (Windows) | Retry with backoff, rm maxRetries |
Practical Edge Cases and Deep Dives
1. Why a half-written JSON file breaks a reader
await writeFile('state.json', JSON.stringify(bigState));
// process killed here -> state.json is empty or truncatedwriteFile opens with O_TRUNC, which empties the file before writing the new bytes. A crash, an ENOSPC, or a concurrent reader between those two moments sees an incomplete file, and JSON.parse throws Unexpected end of JSON input. The temp-file-plus-rename pattern fixes all three: readers either see the old file or the whole new one. fh.sync() before the rename is what makes it survive a power loss — without it the rename can land before the data reaches disk.
2. mkdir first, and the ENOENT that is not a missing file
await writeFile('logs/app/2026-11-15.log', line); // ENOENT: no logs/app directory
await mkdir('logs/app', { recursive: true }); // creates both levels, no error if present
await writeFile('logs/app/2026-11-15.log', line);recursive: true makes mkdir idempotent and returns the first directory it created (or undefined when everything existed), which is safe to call on every write path. writeFile and appendFile never create directories — a service that writes per-tenant paths fails with ENOENT the first time a new tenant appears, and the error message names the file, not the missing directory, which sends people looking in the wrong place.
3. Reading a directory tree without recursion bugs
const files = await readdir('src', { recursive: true, withFileTypes: true });
for (const dirent of files) {
if (!dirent.isFile()) continue;
const full = join(dirent.parentPath, dirent.name);
}withFileTypes returns Dirent objects, so no stat per entry; recursive: true (Node 18.17+) walks subdirectories and sets parentPath. Without it, a hand-written recursion that follows symlinks can loop forever — Dirent.isSymbolicLink() is the check, and lstat rather than stat is the way to inspect a link without following it. On a large tree, streaming the directory (opendir) uses constant memory where readdir materialises every entry.
4. watch and the platform differences that matter
import { watch } from 'node:fs/promises';
for await (const { eventType, filename } of watch('src', { recursive: true })) {
if (eventType === 'change' && filename?.endsWith('.ts')) rebuild(filename);
}fs.watch uses inotify on Linux, FSEvents on macOS, and ReadDirectoryChangesW on Windows, so the same code sees different event coalescing: one edit can produce two change events on macOS and none on a network filesystem. recursive works on macOS and Windows everywhere, on Linux from Node 19.1 onwards with inotify watch limits (fs.inotify.max_user_watches) as a practical ceiling. Watchers also miss events during their startup window, so a build watcher should do one full pass at start, then treat events as hints.
5. Concurrency, EMFILE, and the file-handle limit
async function mapLimit(items, limit, fn) {
const queue = [...items];
const workers = Array.from({ length: limit }, async () => {
while (queue.length) await fn(queue.shift());
});
await Promise.all(workers);
}
await mapLimit(paths, 16, (p) => readFile(p, 'utf8'));Promise.all(paths.map(readFile)) opens every file at once and dies with EMFILE: too many open files at a few thousand. The limit is per process (ulimit -n), and the fix is a concurrency cap plus closing handles — a FileHandle that is never closed leaks one descriptor until GC, so try/finally around open is not optional. For hot paths, a small descriptor pool or readFile (which closes internally) is simpler than caching handles.
6. Streams, signals, and when not to use readFile
import { createReadStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { createGzip } from 'node:zlib';
await pipeline(
createReadStream('big.log'),
createGzip(),
(await import('node:fs')).createWriteStream('big.log.gz'),
);readFile on a file larger than the heap throws ERR_STRING_TOO_LONG or runs out of memory, and even a 200 MB read costs a full allocation and a GC pause. Anything user-sized goes through streams. Both APIs accept an AbortSignal (readFile(p, { signal })), which is how a request handler cancels a file read when the client disconnects; without it the read finishes into a response nobody will receive.
Common Node.js Runtime Mistakes
| Symptom | Cause | Fix |
|---|---|---|
ENOENT on write to a nested path | Parent directory missing | mkdir(dir, { recursive: true }) |
Unexpected end of JSON input after a crash | writeFile truncates before writing | Temp file + rename (+ sync) |
EMFILE under load | Unbounded concurrent opens | Cap concurrency, close handles |
ERR_FS_FILE_TOO_LARGE or OOM | readFile on a huge file | Stream it |
| Watcher misses edits | Platform coalescing, startup window, watch limits | Full pass at start, raise inotify limits |
EACCES on a file the user can read | Different user in the container | Match UID, or fix ownership |
EXDEV on rename | Temp file on another filesystem | Create the temp beside the target |
| Setuid bits lost on copy | copyFile copies mode, not ownership | chmod/chown explicitly |
Directory read returns EISDIR | readFile on a directory | readdir |
| Aborted request still reads the file | No signal passed | Pass req.signal into the fs call |
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.
Node.js Streams: Readable, Writable, Transform, and pipeline
pipe() forwards data but not errors; pipeline() destroys the chain and rejects. Backpressure is the false return from write(), and _flush that never calls back hangs forever.
Node.js crypto: Hashing, HMAC, AES-GCM, and Random Bytes
Hashing, HMAC, AES-256-GCM and randomness solve different problems. Never reuse a GCM nonce, never hash a password with sha256, and compare secrets with timingSafeEqual.
Node.js Buffer and TypedArray: Encodings and Binary Manipulation
A Buffer is a view over an ArrayBuffer, so byteLength is not string length and toString can silently corrupt split UTF-8. allocUnsafe and pooled buffers carry old data.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.