Node Streams: Readable, Writable, Duplex and Transform, Pipelines and Async Iteration
Process data piece by piece instead of all at once: why streams matter, the four stream types, binary, string and object mode, connecting streams with pipe and stream/promises pipeline, writing custom Transform streams, reading with for await, and Readable.from with stream helpers.
kvi5hnuCode Sprout team member6 min readOn this page
The simplest way to process a file is to read it all into memory, transform it, and write the result. That stops working when files are large (a 10 GB log), when many requests do it at once (100 concurrent uploads of 50 MB each), or when you want output to start before input finishes. Streams solve this: data flows through your program in chunks (64 KB by default for file streams), so memory use stays small and constant whatever the total size, and processing starts immediately.
Node uses streams everywhere: files, HTTP requests and responses, TCP sockets, process.stdin/stdout, child process I/O, compression and encryption.
The four stream types

- Readable: a source you read from. Examples:
fs.createReadStream(path),process.stdin, an incoming HTTP request on a server, an HTTP response on a client. - Writable: a destination you write to. Examples:
fs.createWriteStream(path),process.stdout, an outgoing HTTP response. - Duplex: both readable and writable, with independent sides. A TCP socket is duplex: what you write goes to the other computer, and what you read came from it.
- Transform: a duplex stream whose output is computed from its input. Examples:
zlib.createGzip(),crypto.createCipheriv(), a CSV parser.
All streams are EventEmitters (article 125), and each keeps an internal buffer. The highWaterMark option sets how much data the buffer should hold before the stream asks its producer to slow down; that mechanism, backpressure, is the subject of the next article.
By default, streams carry Buffers. A readable stream delivers strings after stream.setEncoding("utf8"), which also decodes multi-byte characters split across chunks correctly (article 124). Streams created with objectMode: true carry arbitrary JavaScript values, one value per chunk; Node's core streams don't use object mode, but parsers and database drivers often do.
Connecting streams: pipeline
Most stream code just moves data from a source through transforms to a destination. Use pipeline from node:stream/promises: it connects the streams, handles backpressure, returns a promise that settles when everything has finished, and on any error destroys all the streams and rejects:
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const zlib = require("node:zlib");
const { pipeline } = require("node:stream/promises");
async function main() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "streams-"));
const log = path.join(dir, "app.log");
fs.writeFileSync(log, "GET /index.html 200\n".repeat(50_000)); // about 1 MB
// Compress a file chunk by chunk: memory use stays small whatever the file size
await pipeline(
fs.createReadStream(log),
zlib.createGzip(),
fs.createWriteStream(log + ".gz"),
);
const before = fs.statSync(log).size, after = fs.statSync(log + ".gz").size;
console.log(before, "bytes; compressed to under 1% of that:", after < before / 100);
// pipeline rejects if any stage fails, and destroys every stream in the chain
try {
await pipeline(fs.createReadStream(path.join(dir, "missing.log")), zlib.createGzip(), fs.createWriteStream(path.join(dir, "x.gz")));
} catch (err) {
console.log("pipeline failed:", err.code);
}
fs.rmSync(dir, { recursive: true });
}
main();
1000000 bytes; compressed to under 1% of that: true
pipeline failed: ENOENT
The older readable.pipe(writable) method, which you'll see in a lot of existing code, also handles backpressure and returns its destination for chaining. However, it does not forward errors: if the source fails, the destination stays open, and every stream needs its own error listener. That leads to file descriptor leaks and hung requests, so prefer pipeline in new code.
pipeline also accepts async generator functions as stages, which is often the quickest way to write a transform:
await pipeline(
fs.createReadStream("data.txt", "utf8"),
async function* (source) {
for await (const chunk of source) yield chunk.toUpperCase();
},
fs.createWriteStream("DATA.txt"),
);
Writing a Transform stream
For a reusable transform, extend Transform (or pass options to its constructor) and implement:
_transform(chunk, encoding, callback): process one chunk,push()zero or more outputs, then callcallback(), orcallback(err)on failure.callback(null, value)is a shortcut for one push._flush(callback)(optional): called after the input ends, to emit anything still held back.
A very common job is splitting text into lines, which never line up with chunk boundaries. The splitter keeps the incomplete last piece and prepends it to the next chunk:
const { Readable, Transform, Writable } = require("node:stream");
const { pipeline } = require("node:stream/promises");
// Splits incoming text into lines, even when a line is cut across chunks
class LineSplitter extends Transform {
#partial = "";
constructor() {
super({ readableObjectMode: true }); // output: one string per line
}
_transform(chunk, encoding, callback) {
const lines = (this.#partial + chunk.toString()).split("\n");
this.#partial = lines.pop(); // last piece may be incomplete
for (const line of lines) this.push(line);
callback();
}
_flush(callback) {
if (this.#partial) this.push(this.#partial);
callback();
}
}
// Keeps only lines that match a pattern (like grep)
const grep = (pattern) => new Transform({
objectMode: true,
transform(line, encoding, callback) {
callback(null, pattern.test(line) ? line : undefined); // undefined: push nothing
},
});
const collected = [];
const sink = new Writable({
objectMode: true,
write(line, encoding, callback) {
collected.push(line);
callback();
},
});
async function main() {
// Chunks deliberately split lines in awkward places
const source = Readable.from(["INFO start\nERR", "OR disk full\nINFO ok\n", "ERROR timeout"]);
await pipeline(source, new LineSplitter(), grep(/^ERROR/), sink);
console.log(collected);
}
main();
[ 'ERROR disk full', 'ERROR timeout' ]
readableObjectMode: true makes the splitter output one string per line, so the next stage works with lines instead of raw bytes. Calling callback() without pushing filters a chunk out. For writing many such programs, node:readline already splits streams into lines: for await (const line of readline.createInterface({ input })).
Reading with for await
Readable streams are async iterables (article 99). A for await loop reads one chunk at a time, waits when no data is available, ends when the stream ends, and throws if the stream emits an error:
const { Readable } = require("node:stream");
async function countWords(stream) {
const counts = new Map();
let partial = "";
for await (const chunk of stream) { // readable streams are async iterables
const words = (partial + chunk).split(/\s+/);
partial = words.pop();
for (const w of words) if (w) counts.set(w, (counts.get(w) ?? 0) + 1);
}
if (partial) counts.set(partial, (counts.get(partial) ?? 0) + 1);
return counts;
}
async function main() {
const text = Readable.from(["the cat sat on th", "e mat the e", "nd"]);
console.log(await countWords(text));
// A readable stream from a generator, plus stream helper methods
async function* numbers() {
for (let i = 1; i <= 10; i++) yield i;
}
const result = await Readable.from(numbers())
.filter((n) => n % 2 === 0)
.map((n) => n * n)
.toArray();
console.log(result);
}
main();
Map(6) {
'the' => 3,
'cat' => 1,
'sat' => 1,
'on' => 1,
'mat' => 1,
'end' => 1
}
[ 4, 16, 36, 64, 100 ]
Readable.from(iterable)makes a readable stream from an array, a generator or an async generator, which is handy for tests and for feeding data into a pipeline.- Readable streams also have helper methods similar to iterator helpers (article 93):
map,filter,flatMap,take,drop,reduce,toArray,forEach,some,every,find.mapandforEachaccept aconcurrencyoption to process several chunks at once, such as several URLs from a list. Some of these are still marked experimental in the Node documentation. - Breaking out of a
for awaitloop destroys the stream, which closes the file or socket.
Async iteration is the easiest way to consume a stream when you need custom processing for each chunk. To write the results to another stream, put the logic in a generator stage of pipeline, as shown earlier, so backpressure is handled for you.
Common questions
When should I use streams instead of readFile?
For small files such as configuration or templates, readFile is simpler. Use streams when data can be large or unbounded (logs, uploads, exports), when serving files over HTTP, or when output should start before input ends.
What's the difference between pipe() and pipeline()?
Both move data with backpressure. pipeline also propagates errors, destroys every stream when one fails, and reports completion through a promise or callback. pipe does neither, so errors need manual handling on every stream.
Why do my lines come out broken when I process chunks?
Chunks are cut at arbitrary byte positions, not at line breaks. Keep the trailing partial line between chunks, as LineSplitter does, or use node:readline.
Summary
- Streams process data in chunks with bounded memory. Types: Readable (source), Writable (destination), Duplex (both, independent) and Transform (output derived from input).
- Chunks are Buffers by default, strings after
setEncoding, or any value inobjectMode. - Connect streams with
pipelinefromnode:stream/promises; it handles backpressure, errors and cleanup. Stages can be streams or async generator functions. - Custom transforms implement
_transformand optionally_flush, usingpushandcallback. - Readable streams are async iterables;
Readable.fromcreates streams from iterables; helpers likemap,filterandtoArraywork on readable streams.
Practice Questions
A server reads a 2 GB video with fs.readFile for each request. What goes wrong with 20 simultaneous viewers, and what's the fix?
Answer
Each request holds the entire 2 GB file in memory, so 20 viewers need about 40 GB, and nothing is sent until each read finishes. Stream it instead: await pipeline(fs.createReadStream(file), res), which sends chunks as they're read with constant memory per request.
Write a pipeline that reads in.txt, converts it to uppercase and writes out.txt.
Answer
const fs = require("node:fs");
const { pipeline } = require("node:stream/promises");
async function main() {
await pipeline(
fs.createReadStream("in.txt", "utf8"),
async function* (source) {
for await (const chunk of source) yield chunk.toUpperCase();
},
fs.createWriteStream("out.txt"),
);
}
main();
Why is setEncoding("utf8") safer than calling chunk.toString() on each chunk yourself?
Answer
A multi-byte UTF-8 character can be split across two chunks. chunk.toString() decodes each half separately and produces replacement characters, while setEncoding holds the incomplete bytes until the next chunk arrives.
What's the difference between a Duplex stream and a Transform stream?
Answer
In a Duplex stream, the readable and writable sides are independent, like the two directions of a TCP socket. In a Transform stream, what you read is computed from what was written, like compressed output from gzip.
Previous: Node Events: EventEmitter, Listeners, Errors and Async Event Helpers
Next: Writing Streams: Backpressure, Flowing and Paused Modes, Custom Streams and Web Streams

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.