2

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?

krlzlx
  • 5,752
  • 14
  • 47
  • 55
sireesha
  • 99
  • 1
  • 1
  • 6
  • What's going wrong when you simply do what's written in [the docs](http://nodeca.github.io/pako/#deflate)? Note that pako has options to compress/decompress to/from string, so your typed array is not necessary. – ASDFGerte Jun 04 '18 at 13:20
  • @ASDFGerte I am doing var str ="Hello world"; var test = pako.gzip(new Uint8Array(str), {to: 'string'}); alert(btoa(test)); I get same output " H4sIAAAAAAAAAwMAAAAAAAAAAAA= " for any string and also not able to get back the original string after decompressing the output. Where am I going wrong? – sireesha Jun 05 '18 at 05:32
  • The way you construct your `Uint8Array` is not working (always empty) - debugging your test for a short moment would quickly tell you that. You could fix that, but way easier is noticing that in `gzip(data[, options])`, data has a described type of "Uint8Array | Array | **String**", which means you can just do `let test = pako.gzip(str, {to: 'string'});`. Reverting the process is as simple as `pako.ungzip(test, { to: 'string' });`. – ASDFGerte Jun 05 '18 at 08:06

2 Answers2

4

Compression:

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

Decompression:

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

Vijay Chavda
  • 826
  • 2
  • 15
  • 34
sireesha
  • 99
  • 1
  • 1
  • 6
  • The compressed string looks like this: `31,139,8,0,0,0,0,0,0,3,203,72,205,201,201,87,200,64,144,0,128,136,249,229,17,0,0,0`, but I think the question is asking for base64 encoded string – recolic Mar 30 '23 at 04:04
0

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

recolic
  • 554
  • 4
  • 18