如何在浏览器中使用 DecompressionStream 使用 JavaScript 解压缩 gzip 文件?

Jay*_*ong 6 javascript web typescript webapi vite

现在所有主要浏览器都支持DecompressionStream API,但我不知道如何使用它fetch()在浏览器中解压缩 gzip 文件。

\n

以下代码适用于 base64 字符串:

\n

\r\n
\r\n
const decompress = async (url) => {\n  const ds = new DecompressionStream(\'gzip\');\n  const response = await fetch(url);\n  const blob_in = await response.blob();\n  const stream_in = blob_in.stream().pipeThrough(ds);\n  const blob_out = await new Response(stream_in).blob();\n  return await blob_out.text();\n};\n\ndecompress(\n  \'data:application/octet-stream;base64,H4sIAAAAAAAAE/NIzcnJVyjPL8pJAQBSntaLCwAAAA==\'\n).then((result) => {\n  console.log(result);\n});
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

但是,如果我在 MacOS 上hello.txt.gz使用创建文件(是内容为“hello world”的纯文本文件),则上面的函数会抛出错误。gzip hello.txthello.txt

\n
decompress(\'/hello.txt.gz\').then((result) => {\n  console.log(result);\n});\n
Run Code Online (Sandbox Code Playgroud)\n
decompress(\'/hello.txt.gz\').then((result) => {\n  console.log(result);\n});\n
Run Code Online (Sandbox Code Playgroud)\n

编辑

\n

Stackblitz有一个可复制的演示。

\n

Jay*_*ong 3

感谢@kaiido\的帮助(见问题评论),我们发现这个错误是由Vite服务器引起的。开发服务器提供.gz带有错误标头的文件。

\n
"content-encoding": "gzip"\n\xe2\x80\x8b\xe2\x80\x8b"content-length": "42"\n"content-type": "text/plain"\n
Run Code Online (Sandbox Code Playgroud)\n

解决方法是重命名文件以使用不同的扩展名(例如hello.txt.gz\xe2\x86\x92 hello.txt.gzip)。

\n

相关Vite问题

\n\n