`title: ReadableStream tee 双路处理与持久化``categories: Web 开发/前端/数据管理``keywords: ReadableStream,tee,Streams,OPFS,持久化``description: 使用 ReadableStream.tee 将输入流拆分为两路,分别用于持久化与实时处理,提升前端数据流水线的扩展性。`场景同时持久化与解析预览,避免重复请求与解码。示例async function saveAndPreview(url, name) {
const res = await fetch(url);
const [a, b] = res.body.tee();
const root = await navigator.storage.getDirectory();
const h = await root.getFileHandle(name, { create: true });
const w = await h.createWritable();
await a.pipeTo(w);
const reader = b.getReader();
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
return new Blob(chunks);
}

发表评论 取消回复