Streams: handling files bigger than memory
Reading a file whole works until the file is bigger than you can hold in memory, and then the process balloons or refuses. Streams read, transform and write in small chunks, and backpressure keeps a fast reader from burying a slow writer. Here is how the pieces fit, and how to see it in your own process.
01 Copying a 600 MB log
You need to copy, compress or filter a log file. The first version reads it whole and writes it back. Here it is on a 600 MB access.log of 12 million lines:
The process grew to the size of the file, because the file was in memory, all at once, in one Buffer. Double the log and the memory doubles. Past 2 GiB, Node will not even try:
All outputs on this page are real runs on Node 24 on a Mac; your exact megabytes will differ. The fix is not more memory. It is never holding more than a small piece of the file at a time.
02 A stream hands you the file in pieces
A stream is data that arrives over time, in chunks, instead of all at once. fs.createReadStream reads the file 64 KiB at a time and passes each chunk on as soon as it has it. fs.createWriteStream accepts chunks and writes them out in order. pipeline connects the two:
Every stream is one of four kinds. You will mostly plug together the ones Node gives you, and occasionally write a Transform of your own.
| Kind | Data goes | Examples |
|---|---|---|
| Readable | out of it | fs.createReadStream, an HTTP request on the server, process.stdin |
| Writable | into it | fs.createWriteStream, an HTTP response, process.stdout |
| Duplex | both ways, unrelated | a TCP socket (net.Socket) |
| Transform | in, changed, out | zlib.createGzip, crypto.createHash, your own |
You can also read a stream with for await. Each pass of the loop gets one chunk. The stream reads ahead only until its own small buffer is full, then waits for the loop to ask for more, so a slow loop body slows the reading down instead of piling chunks up:
599,564,820 bytes in 65,536-byte chunks is 9,148 full chunks and one short one at the end. The 64 KiB size is the stream’s highWaterMark. Since Node 22 it is 64 KiB for every byte stream; before that, generic streams defaulted to 16 KiB and file read streams to 64 KiB. In object mode it counts objects, and the default is 16.
03 Backpressure: when the reader is faster
Reading is often faster than writing: a local disk feeding a slow network, or a quick parser feeding a database. If the reader kept going at full speed, the chunks the writer had not finished would pile up in memory, and you would be back to holding the whole file. Backpressure is how the writer tells the reader to wait.
The signal is the return value of write(). Each writable has a highWaterMark. write() buffers the chunk and returns true while the buffer is below the mark, and false once it reaches it. false means “stop until I emit drain”. The writer emits drain when its buffer has emptied. Here the writer’s mark is set to 128 KiB so you can see both answers; the reader’s own small buffer is left out of the picture.
- chunk being read
- just buffered or written
- still on disk
- read, or waiting
pipeline has connected the file reader to the file writer. Nothing has been read; the write buffer is empty.
You can watch the signal directly with a toy writer that takes 100 ms per chunk and a highWaterMark of 2 bytes:
Notice that write(c) still worked: false is advice, not a refusal. The chunk was accepted and buffered past the mark. Nothing in Node stops you from writing more; respecting the signal is the job of whoever calls write(). pipeline, .pipe() and for await all do it for you.
04 What happens if you ignore it
A loop that calls write() as fast as it can never gives the stream a chance to drain. Every chunk waits in memory, plus the bookkeeping for each one:
The loop is synchronous, so the disk could not write a single chunk before it finished: all 5 million writes were buffered. 61 MB of text cost about a gigabyte of process memory, because each small write is a separate queued request with its own objects. Respect the signal by waiting for drain when write() says false:
The same five million lines, about 170 MB at the peak instead of a gigabyte, and the run took under a second. Waiting costs almost nothing, because the disk was the bottleneck either way.
The same bug hides in HTTP handlers. Writing a big result to res in a loop without checking res.write() buffers it all in memory whenever the client reads slowly. Stream it with pipeline(source, res) instead.
05 Transform: change the data on the way through
A Transform sits in the middle of a pipeline. It gets each chunk, does something with it, and passes on whatever it produces. This one keeps only requests that took 900 ms or more. The catch is that chunks are cut at 64 KiB, not at line ends, so the last line of a chunk is usually incomplete. The transform keeps that piece in rest and puts it in front of the next chunk.
About 93 MB peak to filter 600 MB, and awk on the same file agrees on 1,167,492 lines. Three details make it correct. flush runs once at the end, so a final line without a newline is not lost. Calling done is what lets the next chunk in, so a slow transform applies backpressure to the reader by itself. And encoding: 'utf8' makes the reader hand over strings that never end halfway through a character.
Calling toString() on each chunk decodes the half of é in the first chunk and the half in the second separately, and both come out as the replacement character. Setting an encoding on the stream makes it hold back an incomplete character until the rest arrives.
06 pipe or pipeline: who cleans up on error
a.pipe(b) also handles backpressure, and you will see it in older code. What it does not do is deal with errors. An error on one stream is not passed along, and the others are left open. pipeline destroys every stream in the chain on the first error and reports it once. Here both versions try to gzip a file that does not exist:
const fs = require('node:fs');const zlib = require('node:zlib');const out = fs.createWriteStream('out.gz');fs.createReadStream('missing.log').on('error', (err) => console.log('read failed:', err.code)).pipe(zlib.createGzip()).pipe(out);setTimeout(() => console.log('out.gz closed?', out.closed), 100);// read failed: ENOENT// out.gz closed? false
const fs = require('node:fs');const zlib = require('node:zlib');const { pipeline } = require('node:stream/promises');const out = fs.createWriteStream('out.gz');pipeline(fs.createReadStream('missing.log'), zlib.createGzip(), out).catch((err) => console.log('pipeline failed:', err.code)).then(() => console.log('out.gz closed?', out.closed));// pipeline failed: ENOENT// out.gz closed? true
With .pipe(), the gzip stream and the output file stay open. In a server that leaks a file descriptor per failed request, and if you forget the error handler at all, the unhandled error crashes the process. Use pipeline from node:stream/promises for every chain, and await it inside a try block.
07 When it bites
for (const row of rows) out.write(row);Ignoring the return of write()Everything you write waits in memory if the destination is slower. Check the return value and await once(out, 'drain'), or build a Readable and use pipeline.chunk.toString().split('\n')Treating a chunk as whole linesChunks end at a byte count, not a newline. Keep the unfinished tail for the next chunk, or use readline with for await (const line of rl).text += chunk.toString()Decoding each chunk on its ownA multi-byte character split across chunks turns into garbage. Pass encoding: 'utf8' or call setEncoding('utf8') so the stream decodes across boundaries.src.pipe(gzip).pipe(out).pipe() without error handlingErrors do not travel along the chain and the other streams stay open. Use pipeline and handle its one error.transform(chunk, enc, done) { this.push(x); }Never calling doneThe transform takes no more chunks until done is called, so the pipeline stalls forever with no error. Call it exactly once per chunk, with an error if the chunk failed.new Readable({ objectMode: true })Assuming highWaterMark is bytesIn object mode it counts objects, 16 by default. Sixteen 10 MB objects is 160 MB of buffer. Lower it when each object is large.