Writing Streams: Backpressure, Flowing and Paused Modes, Custom Streams and Web Streams
Write to Node streams correctly: write() and end(), what a false return means, waiting for drain, the cost of ignoring backpressure, flowing vs paused reading modes, implementing custom Readable and Writable streams, destroy and errors, and converting to and from web streams.
kvi5hnuCode Sprout team member6 min readOn this page
The previous article connected streams with pipeline and read them with for await. This one covers what happens underneath: how writing works, how a fast producer is slowed down to match a slow consumer, the two event-based ways of reading, and how to implement your own streams.
Writing: write(), end() and finish
writable.write(chunk, encoding?, callback?)writes a Buffer or string (strings are encoded as UTF-8 unless you pass an encoding). The optional callback runs once the chunk has been handled.writable.end(lastChunk?)writes an optional final chunk and signals that no more data will come. Writing afterend()is an error.- The
finishevent fires when all data has been flushed to the underlying destination, andclosewhen the resource, such as a file descriptor, is released. - As always, listen for
error; a write callback isn't guaranteed to receive errors.
Backpressure
write() always accepts the chunk, and its return value says whether you should continue. It returns true while the stream's buffer is below its highWaterMark (64 KB for byte streams since Node 22, 16 KB in older versions, and 16 objects in object mode) and false once it's full. A false is backpressure: a request to stop writing until the stream emits drain.

const { Writable } = require("node:stream");
const { once } = require("node:events");
// A deliberately slow destination: takes 5 ms per chunk, buffers at most 16 bytes
const slow = new Writable({
highWaterMark: 16,
write(chunk, encoding, callback) {
setTimeout(callback, 5);
},
});
async function main() {
let waits = 0;
for (let i = 0; i < 10; i++) {
const hasRoom = slow.write("eight b\n"); // 8 bytes; always accepted
console.log(`write ${i}: ok=${hasRoom}, buffered=${slow.writableLength}`);
if (!hasRoom) {
waits++;
await once(slow, "drain"); // wait until the buffer empties
}
}
slow.end("last line\n");
await once(slow, "finish");
console.log("finished; paused for drain", waits, "times");
// Ignoring the return value: write() keeps accepting, and memory grows
const careless = new Writable({ highWaterMark: 16, write: (c, e, cb) => setTimeout(cb, 5) });
for (let i = 0; i < 1000; i++) careless.write("eight b\n");
console.log("ignored backpressure; bytes buffered in memory:", careless.writableLength);
careless.destroy();
}
main();
write 0: ok=true, buffered=8
write 1: ok=false, buffered=16
write 2: ok=true, buffered=8
write 3: ok=false, buffered=16
write 4: ok=true, buffered=8
write 5: ok=false, buffered=16
write 6: ok=true, buffered=8
write 7: ok=false, buffered=16
write 8: ok=true, buffered=8
write 9: ok=false, buffered=16
finished; paused for drain 5 times
ignored backpressure; bytes buffered in memory: 8000
With await once(stream, "drain"), the loop pauses whenever the buffer fills, so memory never exceeds roughly the highWaterMark. The careless loop wrote 1,000 chunks into a stream that can handle one every 5 ms, so they all piled up in memory.
On a server, ignoring backpressure is a real security problem, not only an inefficiency. A client can request large responses and then read them very slowly; if the server keeps writing regardless, its memory grows with every such connection until it slows down or crashes. That's a cheap denial-of-service attack. pipeline and pipe handle backpressure automatically, which is the main reason to use them.
Reading with events: two modes
Async iteration and pipeline cover most reading. Two older event-based APIs also exist and appear in a lot of existing code. A readable stream is in one of two modes, and you should use only one API per stream:
- Flowing mode: adding a
datalistener (or callingpipeorresume) starts the flow, and the stream pushes chunks to you as fast as they arrive, followed byend. To apply backpressure manually, callreadable.pause()when a write returnsfalseandreadable.resume()ondrain. - Paused mode: the initial mode. Listen for
readable, then callread()in a loop until it returnsnull. You must drain the buffer completely, or no furtherreadableevent arrives and the program hangs.
const { Readable } = require("node:stream");
const chunks = () => Readable.from(["alpha ", "beta ", "gamma"], { objectMode: false });
// Flowing mode: adding a "data" listener starts the flow
const flowing = chunks();
let text = "";
flowing.on("data", (chunk) => { text += chunk; });
flowing.on("end", () => {
console.log("flowing:", JSON.stringify(text));
// Paused mode: on "readable", call read() until it returns null
const paused = chunks();
const parts = [];
paused.on("readable", () => {
let chunk;
while ((chunk = paused.read()) !== null) parts.push(chunk.toString());
});
paused.on("end", () => console.log("paused:", JSON.stringify(parts.join(""))));
});
flowing.on("error", (err) => console.log("error:", err.message));
flowing: "alpha beta gamma"
paused: "alpha beta gamma"
A stream doesn't emit data until it has a consumer, so data isn't lost if you attach listeners slightly later. Today, for await (paused mode underneath, with backpressure built in) is easier than either API.
Implementing streams
To create your own stream, extend a stream class and implement a few underscore methods, or pass them as options to the constructor:
| Class | Implement | Produce or acknowledge data with |
|---|---|---|
Readable | _read(size) | this.push(chunk); this.push(null) to end |
Writable | _write(chunk, encoding, callback), optional _writev and _final(callback) | callback() when done with the chunk |
Duplex | both _read and _write | both |
Transform | _transform and optional _flush (article 126) | push and callback |
_read is called whenever the consumer wants more data, so a source that only produces on request automatically respects backpressure. _final runs after end() and before finish, which is the place to flush anything held back:
const { Readable, Writable } = require("node:stream");
const { pipeline } = require("node:stream/promises");
const crypto = require("node:crypto");
// A custom Readable: _read is called whenever the consumer wants more data
class Countdown extends Readable {
#n;
constructor(n) {
super({ encoding: "utf8" });
this.#n = n;
}
_read() {
if (this.#n === 0) this.push(null); // null means "end of stream"
else this.push(`${this.#n--}\n`);
}
}
// A custom Writable that hashes everything written to it
class Hasher extends Writable {
#hash = crypto.createHash("sha256");
_write(chunk, encoding, callback) {
this.#hash.update(chunk);
callback();
}
_final(callback) { // runs after end(), before "finish"
this.digest = this.#hash.digest("hex").slice(0, 16);
callback();
}
}
async function main() {
const hasher = new Hasher();
await pipeline(new Countdown(3), hasher);
console.log("hash of '3\\n2\\n1\\n':", hasher.digest);
console.log("same, computed directly:", crypto.createHash("sha256").update("3\n2\n1\n").digest("hex").slice(0, 16));
// Errors: destroy(err) makes the stream emit "error"; pipeline rejects
const broken = new Readable({ read() { this.destroy(new Error("sensor offline")); } });
try {
await pipeline(broken, new Hasher());
} catch (err) {
console.log("pipeline rejected:", err.message);
}
}
main();
hash of '3\n2\n1\n': 43f0a1612c71da4c
same, computed directly: 43f0a1612c71da4c
pipeline rejected: sensor offline
To fail a stream, call stream.destroy(err): it emits error and then close, and pipeline rejects and cleans up every other stream. To find out when any stream is completely done, whether through success, error or premature close, use finished(stream) from node:stream/promises.
For most custom sources, though, Readable.from(asyncGenerator) is simpler than subclassing Readable: a generator only produces the next value when it's asked for one, so backpressure comes for free.
Web streams
Browsers, Deno, Bun and Cloudflare Workers use the WHATWG streams API: ReadableStream, WritableStream and TransformStream (article 117 used them with fetch). Node implements these as globals too, and fetch in Node returns web streams. The two families convert easily:
const { Readable } = require("node:stream");
async function main() {
// A web ReadableStream (the kind fetch() returns), consumed with for await
const web = new ReadableStream({
start(controller) {
controller.enqueue("web ");
controller.enqueue("stream");
controller.close();
},
});
let s = "";
for await (const chunk of web) s += chunk;
console.log(s);
// Node stream -> web stream, then through a web TransformStream
const asWeb = Readable.toWeb(Readable.from(["node ", "to ", "web"]));
const upper = new TransformStream({
transform(chunk, controller) { controller.enqueue(String(chunk).toUpperCase()); },
});
const words = [];
for await (const chunk of asWeb.pipeThrough(upper)) words.push(chunk);
console.log(asWeb instanceof ReadableStream, words.join(""));
// Web stream -> Node stream (for example a fetch body into a file pipeline)
const nodeStream = Readable.fromWeb(new Blob(["blob ", "bytes"]).stream());
const parts = await nodeStream.toArray();
console.log(Buffer.concat(parts).toString());
}
main();
web stream
true NODE TO WEB
blob bytes
Readable.toWeb, Readable.fromWeb, Writable.toWeb and Writable.fromWeb convert between the families. A typical use is saving a downloaded file: await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(path)). For code that must also run outside Node, prefer web streams; Node's own APIs (fs, http, net, zlib) still use Node streams.
Common questions
Does write() returning false mean the data was lost?
No. The chunk was accepted and buffered. false only asks you to stop writing more until drain.
Why does my program hang when reading in paused mode?
You stopped calling read() before it returned null. A new readable event is only emitted after the buffer has been drained.
Do I need to handle drain when I use pipeline?
No. pipeline and pipe pause and resume the source automatically. You only handle drain when you call write() yourself.
Summary
write()buffers every chunk and returnsfalseonce the buffer reacheshighWaterMark; stop andawait once(stream, "drain"). Finish withend()and wait forfinish.- Ignoring backpressure grows memory without limit and can be exploited by slow clients.
pipelinehandles it for you. - Readable streams have flowing mode (
dataevents,pause/resume) and paused mode (readableevents and aread()loop); don't mix them. - Custom streams implement
_readwithpush, or_write/_finalwith callbacks.destroy(err)fails a stream;finishedreports completion. - Web streams (
ReadableStreametc.) work in Node and convert withReadable.toWeb/fromWeb.
Practice Questions
What is wrong with this code that writes a million lines to a file?
const out = fs.createWriteStream("big.txt");
for (let i = 0; i < 1_000_000; i++) out.write(`line ${i}\n`);
out.end();
Answer
It ignores write()'s return value, so all million lines are buffered in memory before much reaches the disk. Inside an async function, wait for drain when a write returns false:
for (let i = 0; i < 1_000_000; i++) {
if (!out.write(`line ${i}\n`)) await once(out, "drain");
}
out.end();
Alternatively, use pipeline(Readable.from(generateLines()), out).
When does a readable stream switch into flowing mode?
Answer
When you add a data listener, call pipe(), or call resume(). Until then it stays in paused mode, and no data is lost.
Implement a Readable that emits the numbers 1 to 5 as strings, one per line, using the constructor options form.
Answer
const { Readable } = require("node:stream");
let n = 1;
const numbers = new Readable({
read() {
this.push(n <= 5 ? `${n++}\n` : null);
},
});
numbers.pipe(process.stdout);
Previous: Node Streams: Readable, Writable, Duplex and Transform, Pipelines and Async Iteration
Next: Node Process and OS Details, File Paths and Reading Files

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.