Skip to content

Streams: handling files bigger than memory

Deep diveConcept

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:

copy-whole.js
const fs = require('node:fs');
const data = fs.readFileSync('access.log'); // the whole file, in memory
fs.writeFileSync('copy.log', data);
const mb = (n) => Math.round(n / 1024 / 1024);
console.log(`peak memory: ${mb(process.resourceUsage().maxRSS * 1024)} MB`);
Shell
$ node copy-whole.js
peak memory: 616 MB

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:

Shell
$ node -e "require('fs').readFile('big.bin', e => console.log(e.code))"
ERR_FS_FILE_TOO_LARGE

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:

copy-stream.js
const fs = require('node:fs');
const { pipeline } = require('node:stream/promises');
async function main() {
await pipeline(
fs.createReadStream('access.log'), // 64 KiB at a time
fs.createWriteStream('copy.log')
);
const mb = (n) => Math.round(n / 1024 / 1024);
console.log(`peak memory: ${mb(process.resourceUsage().maxRSS * 1024)} MB`);
}
main();
Shell
$ node copy-stream.js
peak memory: 77 MB
$ cmp access.log copy.log && echo same
same
readFileSync + writeFileSync616 MBMemory grows with the file. Fails outright above 2 GiB.
pipeline(read stream, write stream)77 MBMostly Node itself. It stays about the same for a bigger file, because only a few chunks are ever in flight.

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.

The four kinds of stream
KindData goesExamples
Readableout of itfs.createReadStream, an HTTP request on the server, process.stdin
Writableinto itfs.createWriteStream, an HTTP response, process.stdout
Duplexboth ways, unrelateda TCP socket (net.Socket)
Transformin, changed, outzlib.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:

for-await.js
const fs = require('node:fs');
async function main() {
let bytes = 0;
let chunks = 0;
for await (const chunk of fs.createReadStream('access.log')) {
bytes += chunk.length; // the next chunk is read only after this body finishes
chunks++;
}
console.log(`${chunks} chunks, ${bytes} bytes`);
}
main();
Shell
$ node for-await.js
9149 chunks, 599564820 bytes

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.

A fast reader, a slow writer, and backpressure
Step 1 of 9
Reader flowingBuffered 0 KiB
access.log · 4 chunks of 64 KiB (a toy file)
c1
c2
c3
c4
Write buffer · highWaterMark 128 KiB
Empty
Written to copy.log
Empty
  • 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.

— last write()

You can watch the signal directly with a toy writer that takes 100 ms per chunk and a highWaterMark of 2 bytes:

drain.js
const { Writable } = require('node:stream');
// A slow destination: each chunk takes 100 ms to "write".
const slow = new Writable({
highWaterMark: 2, // bytes; small so the numbers are easy to read
write(chunk, encoding, done) {
setTimeout(done, 100);
},
});
slow.on('drain', () => console.log('drain: buffer empty, write more'));
for (const c of ['a', 'b', 'c']) {
const ok = slow.write(c);
console.log(`write(${c}) -> ${ok}, buffered ${slow.writableLength}`);
}
Shell
$ node drain.js
write(a) -> true, buffered 1
write(b) -> false, buffered 2
write(c) -> false, buffered 3
drain: buffer empty, write more

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:

ignore.js
const fs = require('node:fs');
const out = fs.createWriteStream('out.log');
for (let i = 0; i < 5_000_000; i++) {
out.write(`line ${i}\n`); // return value ignored
}
const mb = (n) => Math.round(n / 1024 / 1024);
console.log(`waiting in memory: ${mb(out.writableLength)} MB of text`);
console.log(`process memory: ${mb(process.memoryUsage().rss)} MB`);
out.end();
Shell
$ node ignore.js
waiting in memory: 61 MB of text
process memory: 1047 MB

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:

respect.js
const fs = require('node:fs');
const { once } = require('node:events');
async function main() {
const out = fs.createWriteStream('out.log');
for (let i = 0; i < 5_000_000; i++) {
if (!out.write(`line ${i}\n`)) {
await once(out, 'drain'); // wait until the buffer has emptied
}
}
out.end();
}
main();
Shell
$ /usr/bin/time -l node respect.js
0.85 real 0.65 user 0.22 sys
176701440 maximum resident set size
$ wc -l out.log
5000000 out.log

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.

slow-lines.js
const fs = require('node:fs');
const { Transform } = require('node:stream');
const { pipeline } = require('node:stream/promises');
// Keeps only requests that took 900 ms or more.
function slowRequests() {
let rest = ''; // the unfinished line at the end of the last chunk
return new Transform({
transform(chunk, encoding, done) {
const lines = (rest + chunk).split('\n');
rest = lines.pop(); // may be cut in half; wait for the next chunk
const slow = lines.filter((l) => parseInt(l.split(' ').at(-1)) >= 900);
done(null, slow.length ? slow.join('\n') + '\n' : '');
},
flush(done) {
done(null, rest); // the last line, if the file has no final newline
Shell
$ /usr/bin/time -l node slow-lines.js
done
2.31 real 2.18 user 0.26 sys
97501184 maximum resident set size
$ wc -l slow.log
1167492 slow.log

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.

split-char.js
const { Readable } = require('node:stream');
// "café" is 5 bytes in UTF-8: é is two bytes, 0xC3 0xA9.
const bytes = Buffer.from('café');
const chunks = [bytes.subarray(0, 4), bytes.subarray(4)]; // é cut in half
let text = '';
Readable.from(chunks).on('data', (c) => (text += c.toString()))
.on('end', () => console.log('toString per chunk:', text));
const r = Readable.from(chunks);
r.setEncoding('utf8');
let ok = '';
r.on('data', (c) => (ok += c)).on('end', () => console.log('setEncoding:', ok));
Shell
$ node split-char.js
toString per chunk: caf��
setEncoding: café

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:

.pipe()
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
pipeline()
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.

08 Check yourself

Question

out.write(chunk) just returned false. What happened to chunk?

Question

A pipeline reads a 10 GB file from a fast SSD and uploads it over a slow link. Roughly how much of the file is in memory at once?

Question

Your Transform splits each chunk on \n and parses every piece as JSON. It works on small files and fails at random on big ones. Why?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?