netsocket
netsocket

Reputation: 137

How to use zlib.gunzip to turn buffer into readable data?

I'm trying to gunzip a buffer in nodejs, however it keeps returning undefined. Here is my code below:

var options = {
    host: 'api.twitter.com',
    port: 443,
    path: '/2/tweets/search/recent?query=from:twitterdev',
    method: 'GET',
    headers: { "authorization": `Bearer ${token}` }
};

var req = https.request(options, function(res) {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);
    var data = []
    res.on('data', function(d) {
        data.push(d);
    }).on('end',function(){
        var info = Buffer.concat(data)
        console.log(data) <--- This prints the buffer, same with printing info
        zlib.gunzip(info,function(err,buf){
            console.log(buf) <--- Returns undefined
            var o = buf.toString()
            var parsedData = JSON.parse(o)
            console.log(parsedData)
        })
    })

})

req.end();

Reason why i'm not understanding is because var info = Buffer.concat(data) shows the buffer, but its saying the buffer returned from the gunzip is undefined. Not sure how if the buffer is right there. I couldnt find too much on gunzipping, but i did find this thread that didnt help too much How to properly turn buffer object into string?

Upvotes: 2

Views: 2232

Answers (1)

Juergen Kienhoefer
Juergen Kienhoefer

Reputation: 111

I have the same problem right now. My solution would be:

o = zlib.gunzipSync( info );

Would that work for you?

Upvotes: 1

Related Questions