Skip to content

About

Runnable examples from the Node.js Design Patterns article on reading and writing files

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

nodejsdp-write-read-files

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.js

Examples 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.

Examples

fs/promises basics

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

Binary data

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()

Concurrency

File What it shows
05-read-concurrent.js Reading four configs with Promise.all()
06-write-concurrent.js Writing four reports with Promise.all()

Paths and directories

File What it shows
07-directories.js mkdir / readdir / stat
08-script-relative-paths.js import.meta.dirname vs the CWD

Large files

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

Streams

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

Reference

File What it shows
18-best-practices.js Error codes, highWaterMark, closing handles, preferring pipeline()

Which ones actually run

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:

  • 04 takes a path: run 03 first, then node examples/04-read-binary-wav.js beep.wav
  • 11 is meant to fail — there is no massive-dataset.csv, so it prints ENOENT

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.

When to Use Streams

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.

Best Practices Summary

  1. 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.
  2. Use concurrency. Promise.all() when every operation must succeed, Promise.allSettled() when partial failure is acceptable.
  3. Handle specific errors. Catch ENOENT, EACCES, ENOSPC and friends rather than one generic message.
  4. Pick appropriate buffer sizes. The 64 KB highWaterMark default is fine for most cases; raise it for throughput on large datasets.
  5. Always clean up. finally blocks and error handlers so handles and streams close, even on failure.
  6. Use modern patterns. Destructuring, promise chaining, try/catch.

FAQ

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.

Formatting

biome check --write --unsafe .

About

Runnable examples from the Node.js Design Patterns article on reading and writing files

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors