Performance: Stream backpressure concept
This concept affects how fast data flows through streams, impacting memory usage and responsiveness during data processing.
Jump into concepts and practice - no test required
const fs = require('fs'); const readable = fs.createReadStream('largefile.txt'); const writable = fs.createWriteStream('output.txt'); readable.on('data', chunk => { if (!writable.write(chunk)) { readable.pause(); } }); writable.on('drain', () => { readable.resume(); });
const fs = require('fs'); const readable = fs.createReadStream('largefile.txt'); const writable = fs.createWriteStream('output.txt'); readable.on('data', chunk => { writable.write(chunk); });
| Pattern | Memory Usage | Event Loop Blocking | Data Flow Control | Verdict |
|---|---|---|---|---|
| No backpressure handling | High and uncontrolled | Likely blocking | None, data floods buffers | [X] Bad |
| Proper backpressure handling | Controlled and low | Non-blocking | Pauses and resumes flow as needed | [OK] Good |
const readable = getReadableStreamSomehow();
const writable = getWritableStreamSomehow();
readable.on('data', chunk => {
const canWrite = writable.write(chunk);
if (!canWrite) {
readable.pause();
}
});
writable.on('drain', () => {
readable.resume();
});
readable.on('end', () => {
writable.end();
});
What will happen if the writable stream's internal buffer is full?readable.on('data', chunk => {
if (!writable.write(chunk)) {
readable.pause();
}
});
// Missing 'drain' event listener on writable
readable.on('end', () => {
writable.end();
});
What is the main problem causing the readable stream to stay paused?pipe(). Which sequence correctly manages backpressure between a readable and writable stream?