3

I'm getting gzipped data from a business api i'm working with, but I can't manage to decompress it into something readable in JS, though I managed with C#.

My question is - how do I unzip the received gzipped input to a string or json?

The following code works well for me in C#:

using (HttpWebResponse response = (HttpWebResponse)WebRequest.Create(url).GetResponse())
{
    using (GZipStream decompress = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
    {
        using (StreamReader reader = new StreamReader(decompress))
        {
            responseFromServer = reader.ReadToEnd();
        }
    }
}

I've read various answers and tried some libraries but still can't manage to decompress it in JS (using same URL).

This is where the code should be in JS:

var requestData = {
    url: url,
    headers: {
        "Allow-Encoding": "gzip"
    }
}
request.get(requestData, function(error, response, body) {

    // compressed data is in body
});

I've tried pako, zlib but I am probably not using them correctly.

[edit] Some of my tries:

// Decode base64 (convert ascii to binary)
var strData = new Buffer(body).toString('base64');

// 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 strData2 = String.fromCharCode.apply(null, new Uint8Array(data));

This code is running in a NodeJS application, and i'm using request package

Thanks

10
  • You can try github.com/beatgammit/gzip-js Commented Jul 26, 2015 at 12:56
  • I checked that library, but it compresses not decompresses Commented Jul 26, 2015 at 12:58
  • if you look at the source code there is unzip function. Commented Jul 26, 2015 at 12:59
  • @AlexD - what is your question? Commented Jul 26, 2015 at 13:02
  • 1
    Let us continue this discussion in chat. Commented Jul 26, 2015 at 14:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.