Handling 'drain' Events
You'll learn how to properly resume writing data after backpressure pauses your stream operations.
The Problem: When to Write Again?
When you write to a writable stream and write() returns false, you know backpressure is in effect—the stream's internal buffer is full. But how do you know when it's safe to write more data? This is where the 'drain' event comes in.
The 'drain' event is emitted by a writable stream when its internal buffer empties and it's ready to receive more data. Think of it like a sink that was overflowing: once the water drains below a safe level, you can turn the faucet back on.
Listening for 'drain'
When write() returns false, you should pause your writing operations and wait for the 'drain' event before continuing:
const fs = require('fs');
const writable = fs.createWriteStream('output.txt');
function writeMillionRecords() {
let i = 0;
function write() {
let canContinue = true;
while (i < 1000000 && canContinue) {
const chunk = `Record ${i}\n`;
canContinue = writable.write(chunk);
i++;
if (!canContinue) {
// Buffer is full, wait for drain
writable.once('drain', write);
}
}
}
write();
}
writeMillionRecords();
When write() returns false, we stop the loop and attach a 'drain' listener that resumes writing. This prevents memory overflow and respects the stream's capacity.
The Pattern
The typical pattern is: write → check return value → if false, pause and listen for 'drain' → resume when drained.
Key Takeaway: The 'drain' event signals that a writable stream has cleared its buffer and is ready for more data, allowing you to safely resume writing after backpressure.