Node.js › Advanced Node.js
What is backpressure in Node.js streams, and how do you handle it correctly when piping data?
AdvancedAnswer
Backpressure occurs when a writable destination can't consume data as fast as a readable source produces it -- if ignored, unbounded data buffers in memory and can crash the process. Node signals this through the return value of stream.write(), which returns false when the internal buffer has exceeded its highWaterMark; correctly written code pauses the source (or awaits a 'drain' event) until the writable is ready again, which is exactly what .pipe() and pipeline() do automatically.
const canContinue = writable.write(chunk);
if (!canContinue) {
readable.pause();
writable.once('drain', () => readable.resume());
}
// Or, preferably, let pipeline() manage this automatically:
const { pipeline } = require('node:stream/promises');
await pipeline(readable, writable);Real-world example A log-shipping service piping a large file to a slow network socket avoids an out-of-memory crash by using stream.pipeline() instead of manual .on('data') handlers, letting Node's built-in backpressure handling automatically throttle file reads to match the socket's actual write speed.