`title: Compression Streams 压缩与持久化实践(GZIP/Brotli)``categories: Web 开发/前端/数据管理``keywords: Compression Streams,ReadableStream,WritableStream,GZIP,Brotli,OPFS``description: 使用 Compression Streams 在浏览器端对数据进行 GZIP/Brotli 压缩与解压,并结合 OPFS 实现非阻塞持久化,提供特性检测与回退方案。`特性检测function hasCompression() { return typeof CompressionStream !== 'undefined' && typeof DecompressionStream !== 'undefined'; } 压缩到 OPFSasync function gzipToOPFS(name, sourceStream) { const root = await navigator.storage.getDirectory(); const handle = await root.getFileHandle(name, { create: true }); const writable = await handle.createWritable(); await sourceStream.pipeThrough(new CompressionStream('gzip')).pipeTo(writable); } 解压读取async function readAndGunzip(handle) { const file = await handle.getFile(); const stream = file.stream().pipeThrough(new DecompressionStream('gzip')); const reader = stream.getReader(); const chunks = []; while (true) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); } return new Blob(chunks); } 回退方案无压缩流时以 WASM/JS 实现 gzip/brotli,保持流式接口一致。

发表评论 取消回复