getReader Pulls Chunks Until done
A ReadableStream consumer calls reader.read() until done flips true, decoding each Uint8Array chunk with stream:true so multi-byte splits stay intact.
Code
const chunks = ['alpha', 'beta', 'gamma'];
const source = new ReadableStream({
start(controller) {
for (const chunk of chunks) {
controller.enqueue(new TextEncoder().encode(chunk + ';'));
}
controller.close();
},
});
const reader = source.getReader();
const decoder = new TextDecoder();
let text = '';
// read() 每次给回一块 Uint8Array,done 才是终止信号
let next = await reader.read();
while (!next.done) {
// stream:true 保留未完结的多字节序列,等下一块补齐
text += decoder.decode(next.value, { stream: true });
next = await reader.read();
}
console.log(JSON.stringify(text));
console.log('chunks consumed:', chunks.length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
"alpha;beta;gamma;"
chunks consumed: 3Stepwise through the snippet
The core work runs in nested loops — outer for (const chunk of chunks), inner while (!next.done). The async parts await their results, which keeps ordering predictable.
Top-level bindings chunks, source, reader, decoder hold the demo state — nothing sits inside a function scope.
Caveats
- Standard library through and through — drop it in and it executes.
Putting it to use
The run prints chunks consumed: — each prefix names the step that produced it.
Core lines
text += decoder.decode(next.value, { stream: true });
let next = await reader.read();
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `chunks`, `source`, `reader`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.