示例工程 20-network-storage-fetch
20-network-storage-fetch/02-streaming/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— 流式读取:逐块 decode,避免一次性把大响应读进内存
export function streamFromParts(parts) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const part of parts) {
controller.enqueue(typeof part === 'string' ? encoder.encode(part) : part);
}
controller.close();
},
});
}
export async function readChunks(body) {
const reader = body.getReader();
const decoder = new TextDecoder();
const chunks = [];
let text = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const part = decoder.decode(value, { stream: true });
chunks.push(part);
text += part;
}
text += decoder.decode();
return { text, chunks, count: chunks.length, bytes: text.length };
}
export async function run(log = console.log) {
if (typeof fetch !== 'function') {
throw new Error('本示例需要浏览器环境:请通过 index.html 打开');
}
const res = await fetch('./data.txt');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const result = await readChunks(res.body);
log(`读取块数:${result.count}`);
log(`文本长度:${result.text.length}`);
log(`前 40 个字符:${result.text.slice(0, 40)}`);
log('要点:流按块到达,逐块 decode 才能处理跨块的多字节字符。');
return result;
}