[英]Gzip string in javascript using pako.js
I read a topic about decompress a string in javascript using pako.js我阅读了有关使用 pako.js 在 javascript 中解压缩字符串的主题
ZLIB Decompression - Client Side ZLIB 解压 - 客户端
http://jsfiddle.net/9yH7M/1/ http://jsfiddle.net/9yH7M/1/
This is code to decompress这是解压的代码
// Get some base64 encoded binary data from the server. Imagine we got this:
var b64Data = 'H4sIAAAAAAAAAwXB2w0AEBAEwFbWl2Y0IW4jQmziPNo3k6TuGK0Tj/ESVRs6yzkuHRnGIqPB92qzhg8yp62UMAAAAA==';
// Decode base64 (convert ascii to binary)
var strData = atob(b64Data);
// Convert binary string to character-number array
var charData = strData.split('').map(function(x){return x.charCodeAt(0);});
// Turn number array into byte-array
var binData = new Uint8Array(charData);
// Pako magic
var data = pako.inflate(binData);
// Convert gunzipped byteArray back to ascii string:
var strData = String.fromCharCode.apply(null, new Uint16Array(data));
// Output to console
console.log(strData);
I want a method to compress string and ouput can be decompress by above code我想要一种压缩字符串和输出的方法可以通过上面的代码解压缩
How can do that怎么能这样
b64Data
can be simplified:b64Data
解压的代码可以简化:return pako.inflate(atob(b64Data), { to: 'string' });
b64Data
:b64Data
的代码:return btoa(pako.deflate(stringToCompress, { to: 'string' }));
You can do following:您可以执行以下操作:
var binData = pako.deflate( "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")
.map(function(x){return x.charCodeAt(0);}));
yields:产量:
binData : Uint8Array(37) [120, 156, 115, 116, 114, 118, 113, 117, 115, 247, 240, 244, 242, 246, 241, 245, 243, 15, 8, 12, 10, 14, 9, 13, 11, 143, 136, 140, 114, 196, 41, 3, 0, 150, 1, 15, 191]
binData : Uint8Array(37) [120, 156, 115, 116, 114, 118, 113, 117, 115, 247, 240, 244, 242, 246, 241, 245, 1, 1, 14, 10 , 9, 13, 11, 143, 136, 140, 114, 196, 41, 3, 0, 150, 1, 15, 191]
var strData = String.fromCharCode.apply(null, pako.inflate(String.fromCharCode.apply(null, binData).split(""). map(function(x){return x.charCodeAt(0);})));
//yields back
"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.