实现说明
for (const chunk of chunks) 与 while (!next.done) 嵌套——内层在外层的每一步各跑一遍。await 标出每个异步边界——没有 fire-and-forget。
顶层就这几处状态:chunks、source、reader、decoder。
使用要点
- 跑完文件,输出里会留下标记——
chunks consumed:。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件用顶层绑定保存自己的状态:chunks、source、reader。
核心语句
text += decoder.decode(next.value, { stream: true });
let next = await reader.read();
代码示例
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);