我如何ungzip(解压缩)NodeJS请求的模块gzip响应体?

izk*_*izk 63 javascript zlib node.js express

如何在请求的模块响应中解压缩gzipped主体?

我在网上尝试了几个例子,但似乎都没有.

request(url, function(err, response, body) {
    if(err) {
        handleError(err)
    } else {
        if(response.headers['content-encoding'] == 'gzip') {    
            // How can I unzip the gzipped string body variable?
            // For instance, this url:
            // http://highsnobiety.com/2012/08/25/norse-projects-fall-2012-lookbook/
            // Throws error:
            // { [Error: incorrect header check] errno: -3, code: 'Z_DATA_ERROR' }
            // Yet, browser displays page fine and debugger shows its gzipped
            // And unzipped by browser fine...
            if(response.headers['content-encoding'] && response.headers['content-encoding'].toLowerCase().indexOf('gzip') > -1) {   
                var body = response.body;                    
                zlib.gunzip(response.body, function(error, data) {
                    if(!error) {
                        response.body = data.toString();
                    } else {
                        console.log('Error unzipping:');
                        console.log(error);
                        response.body = body;
                    }
                });
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Wea*_*key 54

我也无法获得工作请求,因此最终使用http代替.

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);
});
Run Code Online (Sandbox Code Playgroud)


Ift*_*tah 34

尝试添加encoding: null您传递给的选项request,这将避免将下载的主体转换为字符串并将其保存在二进制缓冲区中.

  • 我有同样的问题,这个编码选项对我有用.谢谢 !! (2认同)

And*_*yer 28

就像@Iftah说的那样encoding: null.

完整示例(减少错误处理):

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);
    }
});
Run Code Online (Sandbox Code Playgroud)


Sai*_*eja 26

实际上,请求模块处理gzip响应.为了告诉请求模块解码回调函数中的body参数,我们必须在选项中将'gzip'设置为true.让我用一个例子来解释你.

例:

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.
})
Run Code Online (Sandbox Code Playgroud)

注意:您在"响应"事件中获得的数据未被解码.

这适合我.希望它也适合你们.

我们在处理请求模块时遇到的类似问题通常是使用JSON解析.让我解释一下.如果您希望请求模块自动解析正文并在body参数中提供JSON内容.然后你必须在选项中将'json'设置为true.

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
})
Run Code Online (Sandbox Code Playgroud)

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

  • 这应该是得到的答案.许多人. (3认同)

Fra*_*her 6

https://gist.github.com/miguelmota/9946206所示

自2017年12月起,请求和请求承诺均立即对其进行处理:

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)
    }
  )
Run Code Online (Sandbox Code Playgroud)


sam*_*ize 5

在尝试了不同的gunzip方法并解决了与编码有关的错误之后,我制定了一个更完整的答案。

希望这也对您有帮助:

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
    }
  }

});
Run Code Online (Sandbox Code Playgroud)