V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
iqoo
V2EX  ›  分享创造

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

  •  
  •   iqoo · 2021-12-08 17:31:30 +08:00 · 2494 次点击
    这是一个创建于 841 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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)
    
    7 条回复    2021-12-09 19:32:03 +08:00
    EPr2hh6LADQWqRVH
        1
    EPr2hh6LADQWqRVH  
       2021-12-08 17:36:05 +08:00
    迷惑行为,http 这层压缩不就完了么,在里面套娃浪费 CPU 干什么
    iqoo
        2
    iqoo  
    OP
       2021-12-08 17:36:50 +08:00
    @avastms 上传呢
    hingbong
        3
    hingbong  
       2021-12-08 19:55:41 +08:00 via Android
    10 行实现 gzip 压缩算法调用啊,还以为能 10 行实现 gzip
    steptodream
        4
    steptodream  
       2021-12-09 08:22:05 +08:00
    抖音上 5 行 py 代码实现坦克大战
    liuidetmks
        5
    liuidetmks  
       2021-12-09 08:35:38 +08:00
    @avastms 有时候参数是加密的,需要先 gzip 再加密.
    liweiliang
        6
    liweiliang  
       2021-12-09 13:54:55 +08:00
    @steptodream 哈哈给整笑了
    newmlp
        7
    newmlp  
       2021-12-09 19:32:03 +08:00
    10 行代码完成 gzip 接口调用,我还以为能把整个压缩算法写出啦
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2668 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:48 · PVG 23:48 · LAX 08:48 · JFK 11:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.