Senior LevelJavaScript & TypeScript
What are JavaScript Streams API (ReadableStream, WritableStream) and backpressure handling?
❓ Interview Prompt: Explain Streams API, chunked data processing, TransformStream piping, and backpressure management.
The Streams API allows processing large data payloads (files, video, HTTP responses) incrementally in small chunks without loading the entire payload into RAM.
Stream Types:
•
`ReadableStream`: Source of data chunks.
•
`WritableStream`: Destination sink for data.
•
`TransformStream`: Transforms chunks while piping from reader to writer.
Backpressure:
Automatic mechanism where a slow consumer signals a fast provider to pause reading chunks until the queue clears, preventing memory exhaustion.
Code Implementation Example
javascript
// Streaming large HTTP download chunk-by-chunk
async function consumeStream(url) {
const response = await fetch(url);
const reader = response.body.getReader();
let totalBytes = 0;
while (true) {
const { done, value } = await reader.read(); // Read single chunk
if (done) break;
totalBytes += value.length;
console.log(`Received chunk of ${value.length} bytes. Total: ${totalBytes}`);
}
}💡Incremental chunked reading of a fetch response stream via ReadableStream reader.
🎯 Interview Key Takeaway
Use Streams API to process large data files incrementally in chunks with built-in backpressure protection.
#Streams API#Performance#Networking#Senior
Back to all JavaScript & TypeScript Questions→