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

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

    Like @Iftah said, set encoding: null.

    Full example (less error handling):

    request = require('request');
    zlib = require('zlib');
    
    request(url, {encoding: null}, function(err, response, body){
        if(response.headers['content-encoding'] == 'gzip'){
            zlib.gunzip(body, function(err, dezipped) {
                callback(dezipped.toString());
            });
        } else {
            callback(body);
        }
    });
    
    0 讨论(0)
  • 2020-11-27 04:43

    I couldn't get request to work either, so ended up using http instead.

    var http = require("http"),
        zlib = require("zlib");
    
    function getGzipped(url, callback) {
        // buffer to store the streamed decompression
        var buffer = [];
    
        http.get(url, function(res) {
            // pipe the response into the gunzip to decompress
            var gunzip = zlib.createGunzip();            
            res.pipe(gunzip);
    
            gunzip.on('data', function(data) {
                // decompression chunk ready, add it to the buffer
                buffer.push(data.toString())
    
            }).on("end", function() {
                // response and decompression complete, join the buffer and return
                callback(null, buffer.join("")); 
    
            }).on("error", function(e) {
                callback(e);
            })
        }).on('error', function(e) {
            callback(e)
        });
    }
    
    getGzipped(url, function(err, data) {
       console.log(data);
    });
    
    0 讨论(0)
  • 2020-11-27 04:44

    As seen in https://gist.github.com/miguelmota/9946206:

    Both request and request-promise handle it out of the box as of Dec 2017:

    var request = require('request')
      request(
        { method: 'GET'
        , uri: 'http://www.google.com'
        , gzip: true
        }
      , function (error, response, body) {
          // body is the decompressed response body
          console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
          console.log('the decoded data is: ' + body)
        }
      )
    
    0 讨论(0)
  • 2020-11-27 04:44

    Here is my two cents worth. I had the same problem and found a cool library called concat-stream:

    let request = require('request');
    const zlib = require('zlib');
    const concat = require('concat-stream');
    
    request(url)
      .pipe(zlib.createGunzip())
      .pipe(concat(stringBuffer => {
        console.log(stringBuffer.toString());
      }));
    
    0 讨论(0)
  • 2020-11-27 04:46

    With got, a request alternative, you can simply do:

    got(url).then(response => {
        console.log(response.body);
    });
    

    Decompression is handled automagically when needed.

    0 讨论(0)
  • 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
        }
      }
    
    });
    
    0 讨论(0)
提交回复
热议问题