You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Base64字符串转换为DecompressionStream可处理的流对象?

Solution

To convert your Buffer into a stream compatible with DecompressionStream, you can create a ReadableStream directly from the Buffer's underlying byte data. Here's the complete working code:

const bpString = "0eJztvVlvJEmS...SPUfzw==";
const buf = Buffer.from(bpString, "base64");

// Convert Buffer to Uint8Array (Buffer is a subclass of Uint8Array, so this is safe)
const uint8Array = new Uint8Array(buf);

// Create a ReadableStream from the byte array
const readableStream = new ReadableStream({
  start(controller) {
    controller.enqueue(uint8Array);
    controller.close();
  }
});

// Decompress the stream using gzip
const decompressedStream = readableStream.pipeThrough(new DecompressionStream("gzip"));

// Read decompressed data as text, then parse to JSON
const decompressedText = await new Response(decompressedStream).text();
const jsonData = JSON.parse(decompressedText);

console.log(jsonData);

Key Details:

  • Buffer to Uint8Array: Browser stream APIs rely on standard Uint8Array instead of Node.js Buffer. Since Buffer inherits from Uint8Array, this conversion is seamless and doesn’t copy data.
  • ReadableStream Setup: The stream emits the entire byte array in one chunk and closes immediately—ideal for in-memory data like your Base64-decoded buffer.
  • Decompression Flow: Piping the readable stream through DecompressionStream handles gzip decompression efficiently without loading the entire decompressed dataset into memory at once.

Why the Fetch Data URL Approach Failed

Browsers enforce strict size limits on data URLs (typically a few megabytes). For large Base64 strings, this method will silently hang or fail because the data URL exceeds the browser’s internal capacity. Using streams directly avoids this limitation entirely.

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:00:08