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

前端 未结 9 1222
日久生厌
日久生厌 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

    I have formulated a more complete answer after trying the different ways to gunzip, and solving errors to do with encoding.

    Hope this helps you too:

    var request = require('request');
    var zlib = require('zlib');
    
    var options = {
      url: 'http://some.endpoint.com/api/',
      headers: {
        'X-some-headers'  : 'Some headers',
        'Accept-Encoding' : 'gzip, deflate',
      },
      encoding: null
    };
    
    request.get(options, function (error, response, body) {
    
      if (!error && response.statusCode == 200) {
        // If response is gzip, unzip first
        var encoding = response.headers['content-encoding']
        if (encoding && encoding.indexOf('gzip') >= 0) {
          zlib.gunzip(body, function(err, dezipped) {
            var json_string = dezipped.toString('utf-8');
            var json = JSON.parse(json_string);
            // Process the json..
          });
        } else {
          // Response is not gzipped
        }
      }
    
    });
    

提交回复
热议问题