The file system with fs/promises
Reading, writing, listing, copying and watching files with node:fs/promises, flags and error codes, glob, atomic writes, and when to use streams instead.
The file system with fs/promises
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `node:fs/promises` is the modern way to touch files: `readFile`, `writeFile`, `appendFile`, `readdir`, `stat`, `mkdir`, `rm`, `cp`, `rename`, `mkdtemp`, `glob` and `watch`, all returning promises you can `await`. The callback and `Sync` forms in `node:fs` do the same jobs.
- `readFile` returns a `Buffer` unless you pass an encoding such as `'utf8'`. `readFile` and `writeFile` load or hold the whole file in memory, so use streams for anything large.
- Failures arrive as errors with a `code` (`ENOENT`, `EEXIST`, `EISDIR`, `EACCES`, `ENOTEMPTY`). Branch on `error.code`, never on the message text. Do not check `exists` first and then act; attempt the operation and handle the error.
- The `flag` option controls how a file is opened: `'w'` truncates, `'a'` appends, `'wx'` fails if the file already exists. `mode` sets permissions on creation, for example `0o600` for a private file.
- To avoid a half-written file when the process dies mid-write, write to a temporary file in the same directory and `rename` it over the target. A rename within one file system is atomic.
Three styles of one API
The node:fs module has the same operations in three forms, and you will meet all of them in old code:
import fs from 'node:fs';
import { readFile } from 'node:fs/promises';
fs.readFile('a.txt', 'utf8', (err, text) => { /* callback: error first */ });
const text1 = fs.readFileSync('a.txt', 'utf8'); // blocks the event loop
const text2 = await readFile('a.txt', 'utf8'); // promise
The callback form is the original; its (err, data) convention is explained in error-first callbacks and promisify. The Sync form blocks the loop, which is fine at startup and in scripts and a bug in a request handler (blocking vs non-blocking I/O). The promise form from node:fs/promises is what new code should use. fs.promises is the same object, so import { readFile } from 'node:fs/promises' and fs.promises.readFile are interchangeable.
The everyday operations
This script was run on Node 26.13.1:
import { readFile, writeFile, appendFile, mkdir, readdir, stat, cp, rm, mkdtemp } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'demo-')); // a unique scratch directory
await mkdir(join(dir, 'a/b'), { recursive: true }); // like mkdir -p
await writeFile(join(dir, 'a/note.txt'), 'hello\n');
await appendFile(join(dir, 'a/note.txt'), 'world\n');
console.log(JSON.stringify(await readFile(join(dir, 'a/note.txt'), 'utf8'))); // "hello\nworld\n"
const s = await stat(join(dir, 'a/note.txt'));
console.log(s.isFile(), s.size, s.mtime instanceof Date); // true 12 true
const entries = await readdir(join(dir, 'a'), { withFileTypes: true });
console.log(entries.map(d => `${d.name}:${d.isDirectory() ? 'dir' : 'file'}`)); // [ 'b:dir', 'note.txt:file' ]
await cp(join(dir, 'a'), join(dir, 'copy'), { recursive: true });
console.log((await readdir(dir, { recursive: true })).sort());
await rm(dir, { recursive: true, force: true }); // like rm -rf; no error if missing
A few details worth remembering. mkdir with recursive: true creates parents and does not fail if the directory exists. readdir with withFileTypes returns Dirent objects so you do not need a stat per entry, and recursive: true walks subdirectories. cp copies whole directories and rm with force ignores a missing path. rename moves files within a file system. Paths are plain strings; building them correctly is the subject of path, os and URL modules.
Because the promises are independent, you can run many at once:
const names = Array.from({ length: 50 }, (_, i) => join(dir, `f${i}.txt`));
await Promise.all(names.map((n, i) => writeFile(n, String(i))));
That works, but files go through the libuv thread pool of four threads, so fifty at once simply queue. For thousands of files, limit concurrency.
Matching files with glob
fs.promises.glob returns an async iterator of paths matching a pattern:
import { glob } from 'node:fs/promises';
for await (const f of glob('**/*.txt', { cwd: dir })) console.log(f);
On Node 26.13.1 this runs without an experimental warning. It arrived in Node 22 as experimental, so on older lines expect a warning, and check the docs for the stability of your version.
Errors and flags
Failures are Error objects with a code property, and code is what you branch on:
try {
await readFile('/nonexistent');
} catch (err) {
if (err.code === 'ENOENT') { /* file missing */ } else throw err;
}
The codes you will meet most: ENOENT (missing), EEXIST (already exists), EISDIR (it is a directory), ENOTEMPTY (cannot remove a non-empty directory with rmdir), EACCES and EPERM (permissions). All appeared in testing.
Do not write “check if it exists, then read”. Between the check and the read, another process can remove the file, so the check cannot be trusted. Attempt the operation and handle the error. The same logic applies to creating files:
await writeFile(path, 'x', { flag: 'wx' }); // fails with EEXIST if present
await writeFile(path, 'x', { mode: 0o600 }); // created as owner read/write only
'w' (default) truncates, 'a' appends, and 'wx' creates exclusively. In a test, mode: 0o600 produced a file whose permission bits read 600.
Safe writes: temp file and rename
If the process is killed during writeFile, the target can be left half-written. For files that must never be corrupt, write somewhere else and swap:
import { writeFile, rename, rm } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { join, dirname } from 'node:path';
async function writeFileAtomic(path, data) {
const tmp = join(dirname(path), `.${randomUUID()}.tmp`);
try { await writeFile(tmp, data); await rename(tmp, path); }
catch (e) { await rm(tmp, { force: true }); throw e; }
}
The temporary file lives in the same directory so rename stays on one file system, where it is atomic: readers see the old file or the new one, never half of either. Two calls in a test left only config.json with the second version.
Big files, watching, and file handles
readFile and writeFile hold the whole file in memory. For large inputs, stream. await open(path) gives a FileHandle, whose readLines() is an async iterator over lines, and createReadStream feeds streams. fs.promises.watch(dir, { signal }) is an async iterator of change events, ended with an AbortController; the event types and file names vary by operating system, and the docs list its caveats. In development, node --watch is usually what you want instead.
What the video covers
Codevolution’s five-minute video covers the promise-based file API with async and await, at an introductory level. It is from December 2022. glob, cp, permissions, atomic writes and streams are in the prose, and his 12-minute callback-style video under “go deeper” covers the older forms. No transcript was available. The callback versions in that video still work on current Node.
Where this fits
Files are the first standard-library module most people use. Next come the helpers that surround them: path, os and URL. For loading configuration files and secrets safely, see secrets and sensitive data handling.
Check yourself
What is the difference between `await readFile(path)` and `await readFile(path, 'utf8')`?
Without an encoding you get a `Buffer` of raw bytes. With `'utf8'` you get a decoded string. Pass the encoding when the file is text, and leave it off for binary data such as images.
Why is `if (await exists(path)) { await readFile(path) }` considered a bug-prone pattern?
Another process can delete or create the file between the check and the use (a race), so the check proves nothing. It is also an extra system call. Call `readFile` directly inside `try`/`catch` and handle `ENOENT`.
How does `writeFile(path, data, { flag: 'wx' })` behave differently from the default?
The default flag `'w'` creates the file or truncates an existing one. `'wx'` fails with `EEXIST` if the file already exists, which makes it a safe way to create a lock file or avoid overwriting data.
You are asked to process a 4 GB log file line by line. Why is `readFile` the wrong tool, and what replaces it?
`readFile` allocates memory for the entire file, which can exceed the process's limits or cause heavy garbage collection. Open the file and read it as a stream, for example with `createReadStream`, or `fileHandle.readLines()`, so only a small chunk is in memory at a time.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.