Reading Chunks with read()
You'll learn how to use reader.read() to pull data from a stream piece-by-piece, handling it as it arrives rather than waiting for the entire response.
What You Already Have
By now, you've obtained a ReadableStream from response.body and called getReader() to lock onto that stream. Now you need to actually read the chunks flowing through.
The read() Method
The reader.read() method is your tool for retrieving chunks asynchronously. Each call returns a Promise that resolves to an object with two properties:
done: A boolean indicating whether the stream has finished (true) or more data is coming (false)value: AUint8Arraycontaining the actual chunk of data (only present whendoneisfalse)
Think of it like checking your mailbox: each time you call read(), you're asking "Is there mail? If so, give it to me. If not, tell me we're done."
How It Works
const response = await fetch('https://example.com/large-file');
const reader = response.body.getReader();
const chunk = await reader.read();
console.log(chunk.done); // false (if data remains)
console.log(chunk.value); // Uint8Array [...]
To process an entire stream, you repeatedly call read() until done becomes true:
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log('Stream complete');
break;
}
console.log('Received chunk:', value.length, 'bytes');
}
Each iteration pulls the next available chunk. When the server finishes sending data, done flips to true and value is undefined.
Key Takeaway: reader.read() returns a promise resolving to {done, value}, letting you process streaming data chunk-by-chunk as it arrives instead of waiting for the entire payload.