Gzip a string in javascript using pako.js

14.6k Views Asked by At

I was able to decompress a string in JavaScript using pako.js

http://jsfiddle.net/9yH7M/1/

// 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 output can be decompressed by above code using pako and gzip.

How can I do that?

2

There are 2 best solutions below

2
On

Compression:

let compressed_str = pako.gzip(str, {to: 'string'});

Decompression:

let original_str = pako.ungzip(compressed_str, { to: 'string' });

0
On

There is a duplicate question, so I'm sharing my answer here.

https://stackoverflow.com/a/75934779/7295761

{to: 'string'} simply doesn't work for latest pako.js