Stream large files in Node.js without spiking memory
Use fs.createReadStream and pipe() to move large files in chunks, keeping Node.js memory usage flat instead of loading everything into RAM.
11 Sept 2026, 10:04 UTC

A multi-gigabyte log file should not require multi-gigabyte RAM
A common Node.js script reads an entire file with fs.readFileSync(), processes the text, and writes it out. That works until the file is larger than available memory. The process slows, swaps, or crashes with an out-of-memory error even though the logic only needs to look at one line at a time.
The practical fix is to stream: read the file in small chunks, pass each chunk onward, and let Node manage when to pause and resume. You avoid loading the whole file into RAM at once.
What streaming means in Node.js
A readable stream is an EventEmitter that produces data piece by piece instead of returning one buffer. A writable stream accepts those pieces. Backpressure is the signal that tells the source to slow down when the destination cannot keep up. The highWaterMark option sets the internal buffer size; the default is 64 KB, which suits many disk and network workloads but can be tuned.
Worked example: copy a large file without a memory spike
Run this script in a terminal where the Node.js process has read permission on the source file and write permission on the destination path.
const fs = require('fs');
const source = process.argv[2] || '/path/to/large-input.log';
const destination = process.argv[3] || '/path/to/large-output.log';
const readStream = fs.createReadStream(source, { highWaterMark: 64 * 1024 });
const writeStream = fs.createWriteStream(destination);
readStream.on('error', (err) => {
console.error('Read error:', err.message);
process.exit(1);
});
writeStream.on('error', (err) => {
console.error('Write error:', err.message);
process.exit(1);
});
writeStream.on('finish', () => {
console.log('Copy finished');
});
readStream.pipe(writeStream);
pipe() connects the readable stream to the writable stream and handles chunk flow and end-of-file events. To verify, start the script, then check the Node process with top -p <pid> or ps in another terminal. Resident memory should stay roughly flat as the file grows. The finish event fires after the final chunk is flushed to disk.
Errors do not surface by themselves
Node treats an unhandled error event on an EventEmitter as an uncaught exception that can exit the process. If you omit the error listener on readStream, a missing file or permission denial crashes the program. Attach listeners to both streams because pipe() does not automatically forward every error between endpoints in all patterns.
Limitations: streaming is not always the right tool
- Streaming avoids memory bloat, but CPU-heavy work inside a
datahandler blocks the event loop. Offload transformations to worker threads or asynchronous functions. - If your logic needs random access to distant parts of the same file, a stream is the wrong abstraction; read the file or use an indexed store.
- A pipe chain can hang if an intermediate stream never emits
finishorend.
Check the result
- Create a 50 MB test file:
head -c 50M /dev/zero > /tmp/stream-test.bin(requires shell access and write permission to/tmp). - Run the copy script with that file as the source.
- Monitor the Node process with
topornode --inspectand confirm memory does not scale with file size. - Compare source and destination byte counts with
wc -c.
Because this script writes a file, a failed stream can leave a partial destination. Remove the incomplete output manually before retrying. For routine large-file handling in Node.js, start with createReadStream and pipe(), handle errors on both ends, and watch memory rather than assuming the file fits in RAM.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.