Handling Write Backpressure
You'll learn how to check the return value of write() to detect when the stream's buffer is full and you should pause writing.
What Is Backpressure?
When you write data to a writable stream, it gets buffered internally before being flushed to its destination (a file, network socket, etc.). If you write data faster than the stream can flush it, the buffer fills up. This situation is called backpressure — the stream is pushing back, signaling "slow down!"
The write() Return Value
Every call to stream.write(chunk) returns a boolean:
true: The buffer has room. You can keep writing.false: The buffer is full. You should pause and wait for it to drain.
Ignoring false won't crash your program immediately, but it can cause memory issues as Node buffers unlimited data in RAM.
How to Handle It
When write() returns false, stop writing and listen for the 'drain' event. This event fires when the buffer has emptied and is ready for more data:
const fs = require('fs');
const writable = fs.createWriteStream('output.txt');
function writeMillionTimes(writer, data, encoding) {
let i = 1000000;
write();
function write() {
let ok = true;
while (i > 0 && ok) {
i--;
ok = writer.write(data, encoding);
}
if (i > 0) {
// Buffer full! Wait for drain
writer.once('drain', write);
}
}
}
writeMillionTimes(writable, 'hello\n', 'utf8');
When ok becomes false, we stop the loop and resume only after 'drain' fires.
Key Takeaway: Always check the return value of write() — if it's false, stop writing and wait for the 'drain' event to avoid overwhelming the buffer.