如何将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
Uint8Arrayinstead of Node.jsBuffer. SinceBufferinherits fromUint8Array, 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
DecompressionStreamhandles 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
相关产品推荐
相关产品推荐

