Backpressure helps prevent the writable stream from being flooded with data it cannot handle immediately. It signals the readable stream to slow down or pause until the writable stream is ready again.
When writable.write() returns false, it signals that the internal buffer is full. The readable stream should pause to avoid overwhelming the writable stream.
const { Readable, Writable } = require('stream');
const readable = new Readable({
read() {
this.push('data');
this.push(null);
}
});
const writable = new Writable({
write(chunk, encoding, callback) {
console.log('Writing:', chunk.toString());
callback();
}
});
const canWriteMore = writable.write('chunk1');
console.log('Can write more after chunk1:', canWriteMore);
writable.on('drain', () => {
console.log('Drain event fired');
});Since the writable stream's internal buffer is empty and the write is synchronous, writable.write returns true immediately. The 'drain' event does not fire because the buffer never fills.
const fs = require('fs'); const readable = fs.createReadStream('input.txt'); const writable = fs.createWriteStream('output.txt'); readable.on('data', (chunk) => { writable.write(chunk); });
If writable.write returns false, the writable stream's buffer is full. Without pausing the readable stream, data keeps accumulating in memory causing a leak.
Option A checks writable.write's return value and pauses the readable stream if false, then resumes it on 'drain'. This correctly manages backpressure.