Runnable examples from Reading and Writing Files in Node.js (Node.js Design Patterns).
Requires Node.js 20.11+ for import.meta.dirname; this repo pins the latest LTS in .nvmrc.
nvm use
node examples/01-read-file.jsExamples write their output to the current working directory, so run them from
a scratch directory if you do not want user-data.json, beep.wav,
voucher-codes.txt or reports/ landing in the repo root.
| File | What it shows |
|---|---|
| 01-read-file.js | readFile() — whole file into memory, string vs Buffer |
| 02-write-file.js | writeFile() — one shot, creates or truncates |
| 09-sync-operations.js | readFileSync / writeFileSync and why they block |
| File | What it shows |
|---|---|
| 03-write-binary-wav.js | Building a WAV file with Buffer.alloc() and write*LE() |
| 04-read-binary-wav.js | Parsing RIFF chunks back out with read*LE() |
| File | What it shows |
|---|---|
| 05-read-concurrent.js | Reading four configs with Promise.all() |
| 06-write-concurrent.js | Writing four reports with Promise.all() |
| File | What it shows |
|---|---|
| 07-directories.js | mkdir / readdir / stat |
| 08-script-relative-paths.js | import.meta.dirname vs the CWD |
| File | What it shows |
|---|---|
| 10-buffer-limits.js | buffer.constants.MAX_LENGTH |
| 11-large-file-errors.js | ERR_FS_FILE_TOO_LARGE and ENOMEM |
| 12-file-handle-read-chunks.js | open() + read() at an explicit position |
| 13-file-handle-write-chunks.js | open() + write() chunk by chunk |
| File | What it shows |
|---|---|
| 14-read-stream.js | createReadStream() and the data / end / error events |
| 15-write-stream-backpressure.js | write() returning false, waiting for drain |
| 16-pipeline-readable-class.js | pipeline() with a custom Readable |
| 17-pipeline-generator.js | Same result from a plain generator |
| File | What it shows |
|---|---|
| 18-best-practices.js | Error codes, highWaterMark, closing handles, preferring pipeline() |
All of them. 01, 05, 07, 08, 09, 12 and 14 read the fixtures
committed under examples/ (config.json, config/, templates/, uploads/).
Two need a little setup:
04takes a path: run03first, thennode examples/04-read-binary-wav.js beep.wav11is meant to fail — there is nomassive-dataset.csv, so it printsENOENT
13, 15, 16 and 17 each generate 1,000,000 voucher codes (~9 MB, about a
second) and all write to the same voucher-codes.txt.
Reach for streams when you have:
- Large files — anything over ~100 MB
- Real-time data: logs, live feeds
- Memory-constrained environments: cloud functions, containers
- Multiple processing steps that need to compose
- Unknown file sizes: user uploads, network data
Streams give you the memory efficiency of low-level file operations with a much more ergonomic API.
- Match the approach to the use case.
- Small files:
fs/promises. - Large files: streams.
- Precise control: file handles.
- CLI tools can use the sync methods;
- concurrent apps must not.
- Small files:
- Use concurrency.
Promise.all()when every operation must succeed,Promise.allSettled()when partial failure is acceptable. - Handle specific errors. Catch
ENOENT,EACCES,ENOSPCand friends rather than one generic message. - Pick appropriate buffer sizes. The 64 KB
highWaterMarkdefault is fine for most cases; raise it for throughput on large datasets. - Always clean up.
finallyblocks and error handlers so handles and streams close, even on failure. - Use modern patterns. Destructuring, promise chaining,
try/catch.
What is the difference between sync and async file operations? Sync operations block the event loop until they finish, so nothing else runs. Async operations do not. Async is mandatory for web servers and any concurrent application.
How do I handle large files efficiently?
Past ~100 MB, avoid readFile() and writeFile() — they load the whole file
into memory. Use streams, or file handles with manual chunking. Streams are
preferred because they handle backpressure for you.
When should I use streams instead of promises? Promises for small-to-medium files where you need the complete content, such as config files. Streams for large files, real-time processing, tight memory budgets, and anywhere you want to transform or chain operations.
Which error codes should I handle?
ENOENT (missing file), EACCES (permissions), EISDIR (path is a directory),
ENOSPC (disk full), EMFILE (out of file descriptors).
Can I use top-level await?
Yes, in ES modules on modern Node.js — every example here does. No async
wrapper function required.
How do I process multiple files concurrently?
Map to an array of promises and pass it to Promise.all() or
Promise.allSettled(). For I/O-bound work this is much faster than a sequential
loop. See examples 05 and 06.
biome check --write --unsafe .