When building scalable backends, you cannot predict the size of data clients will send or request. Loading entire files into memory with fs.readFile() works for small JSON files, but will instantly crash your server with an ERR_BUFFER_TOO_LARGE or out-of-memory error when handling 1GB+ files. Node.js Streams process data continuously in small, bite-sized chunks.
| Stream Type | Description | Standard Library Example |
|---|---|---|
| Readable | Stream from which data can be read chunk-by-chunk. | fs.createReadStream, http.IncomingMessage (req) |
| Writable | Stream to which data can be written sequentially. | fs.createWriteStream, http.ServerResponse (res) |
| Duplex | Stream that is both Readable and Writable simultaneously. | net.Socket (TCP network socket) |
| Transform | A Duplex stream that modifies or transforms data as it is read and written. | zlib.createGzip, crypto.createCipheriv |
stream.promises.pipelineThe pipeline() function connects streams together and handles error propagation and cleanup automatically:
import fs from 'node:fs';
import { pipeline } from 'node:stream/promises';
import zlib from 'node:zlib';
async function compressLargeFile(sourceFile, destinationArchive) {
try {
console.log('Starting stream compression pipeline...');
await pipeline(
fs.createReadStream(sourceFile), // 1. Read chunks (64 KB each)
zlib.createGzip(), // 2. Compress chunks on the fly
fs.createWriteStream(destinationArchive) // 3. Write compressed gzip bytes
);
console.log('[SUCCESS] File compressed without RAM overflow!');
} catch (err) {
console.error('[FAILED] Pipeline failed:', err.message);
}
}
compressLargeFile('large-server-log.csv', 'large-server-log.csv.gz');
Transform streams allow real-time filtering, data masking, or CSV-to-JSON parsing:
import { Transform } from 'node:stream';
// A Transform stream that converts incoming text to UPPERCASE
const upperCaseStream = new Transform({
transform(chunk, encoding, callback) {
const upperText = chunk.toString().toUpperCase();
this.push(upperText); // Forward transformed chunk to the next stream
callback(); // Signal ready for the next chunk
}
});
process.stdin.pipe(upperCaseStream).pipe(process.stdout);
// Type in terminal: "hello veewom" > Outputs: "HELLO VEEWOM"
Q: What is the highWaterMark option in Node.js streams?
A: highWaterMark specifies the maximum buffer threshold (in bytes) that a stream will hold in memory before it stops reading from the underlying resource. For normal Readable streams, the default is 64 KB (16 KB for Writable streams). When this limit is reached, backpressure is triggered until the buffer drains.
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Streams transfer binary Buffer chunks sequentially.
fs.createReadStream and fs.createWriteStream methods.
Compress gigabyte files on the fly using zlib Transform streams.