How do I ungzip (decompress) a NodeJS request's module gzip response body?

前端 未结 9 1024
日久生厌
日久生厌 2020-11-27 04:21

How do I unzip a gzipped body in a request\'s module response?

I have tried several examples around the web but none of them appear to work.

request(         


        
相关标签:
9条回答
  • 2020-11-27 04:50

    Here's a working example (using the request module for node) that gunzips the response

    function gunzipJSON(response){
    
        var gunzip = zlib.createGunzip();
        var json = "";
    
        gunzip.on('data', function(data){
            json += data.toString();
        });
    
        gunzip.on('end', function(){
            parseJSON(json);
        });
    
        response.pipe(gunzip);
    }
    

    Full code: https://gist.github.com/0xPr0xy/5002984

    0 讨论(0)
  • 2020-11-27 04:56

    try adding encoding: null to the options you pass to request, this will avoid converting the downloaded body to a string and keep it in a binary buffer.

    0 讨论(0)
  • 2020-11-27 04:56

    Actually request module handles the gzip response. In order to tell the request module to decode the body argument in the callback function, We have to set the 'gzip' to true in the options. Let me explain you with an example.

    Example:

    var opts = {
      uri: 'some uri which return gzip data',
      gzip: true
    }
    
    request(opts, function (err, res, body) {
     // now body and res.body both will contain decoded content.
    })
    

    Note: The data you get on 'reponse' event is not decoded.

    This works for me. Hope it works for you guys too.

    The similar problem usually we ran into while working with request module is with JSON parsing. Let me explain it. If u want request module to automatically parse the body and provide you JSON content in the body argument. Then you have to set 'json' to true in the options.

    var opts = {
      uri:'some uri that provides json data', 
      json: true
    } 
    request(opts, function (err, res, body) {
    // body and res.body will contain json content
    })
    

    Reference: https://www.npmjs.com/package/request#requestoptions-callback

    0 讨论(0)
提交回复
热议问题