JavaScript: Decompress / inflate /unzip /ungzip strings [closed]

感情迁移 提交于 2019-11-28 06:17:29
Sean Kinsey

Take a look at this Stack Overflow question, the answers there contains references to multiple compressing engines implemented in javascript. Most of these are based on LZ77.

I don't know how you'd like that, but I like these implementations:

The first is fastest than second, We can usually ensure a fast server, however we don't know the performance of the client machine. Therefore I recommend you choose js-deflate and adjust your java (server side) to inflate.

https://github.com/dankogai/js-deflate

http://code.google.com/p/gzipjs/

I created a working example using pako, modern and fast Zlib port. http://jsfiddle.net/9yH7M/2/

there's this graphing library that has as part of it, a zlib implementation in javascript. if you scroll down this page a bit, you'll see it as a separate download. http://jsxgraph.uni-bayreuth.de/wp/download/

This example: http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip shows how you can do ZIP files in Javascript. Now, I know you want ZLIB or DEFLATE compression, rather than ZIP. But, ZIP uses DEFLATE, and within the .js file for that example, there is an InflatingReader class that can INFLATE as it reads.

The class exposes these methods:

readByte()
   returns null when EOF is reached, or the value of the byte when successful.

readToEnd()
   returns an array of all bytes read, to EOF

beginReadToEnd(callback)
   async version of the above

readBytes(n)
   returns an array of n bytes read from the source.

beginReadBytes(n, callback)
   async version of the above

You can use that code unchanged if you want INFLATE.

If you want ZLIB (aka unzip), then there is a 2-byte signature that you need to read and validate before reading the compressed bytes and doing the INFLATE. Just modify the InflatingReader to read and dump 2 bytes, and it will do ZLIB just fine.

I found a working inflate implementation here:

http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt

If you want a slightly cleaner version that namespaces the algorithm, this one should work:

https://github.com/augustl/js-inflate

Keep in mind that gzipped "inflate" data is prefixed with a two-byte header, and suffixed with a four-byte checksum, which you will need to strip before passing to the algorithm.

Don't do that in JavaScript. It'd be slow and besides that JS doesn't do well with binary data.

Simply use gzip transfer encoding on the server side and your browser will take care of decompressing it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!