10 行 JS 代码实现 gzip 压缩/解压缩

2021-12-08 17:31:30 +08:00
 iqoo

Chrome80+ 支持原生的 gzip 压缩 /解压缩,支持流模式。一个简单的用法:

function gzipImpl(cls, algo, data) {
  const {writable, readable} = new cls(algo)
  const writer = writable.getWriter()
  writer
    .write(data)
    .then(_ => writer.close())
  return new Response(readable).arrayBuffer()
}
const gzip = gzipImpl.bind(0, CompressionStream, 'gzip')
const gunzip = gzipImpl.bind(0, DecompressionStream, 'gzip')

// test
const srcData = new Uint8Array(10000)
const zipData = await gzip(srcData)
const unzipData = await gunzip(zipData)

// src: 10000 zip: 45
console.log('src:', srcData.length, 'zip:', zipData.byteLength)
console.assert(srcData.length === unzipData.byteLength)
2506 次点击
所在节点    分享创造
7 条回复
EPr2hh6LADQWqRVH
2021-12-08 17:36:05 +08:00
迷惑行为,http 这层压缩不就完了么,在里面套娃浪费 CPU 干什么
iqoo
2021-12-08 17:36:50 +08:00
@avastms 上传呢
hingbong
2021-12-08 19:55:41 +08:00
10 行实现 gzip 压缩算法调用啊,还以为能 10 行实现 gzip
steptodream
2021-12-09 08:22:05 +08:00
抖音上 5 行 py 代码实现坦克大战
liuidetmks
2021-12-09 08:35:38 +08:00
@avastms 有时候参数是加密的,需要先 gzip 再加密.
liweiliang
2021-12-09 13:54:55 +08:00
@steptodream 哈哈给整笑了
newmlp
2021-12-09 19:32:03 +08:00
10 行代码完成 gzip 接口调用,我还以为能把整个压缩算法写出啦

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/820923

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX