How to use request or http module to read gzip page into a string

前端 未结 5 1318
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 05:09

I found the request module in js cannot handle gzip or inflate format http response correctly.

for example:

request({url:\'some url\'}, function (err         


        
5条回答
  •  抹茶落季
    2020-12-09 06:01

    simplified example:

    var https = require('https');
    var gunzip = require('zlib').createGunzip();
    
    var options = {
        host: 'api.stackexchange.com',
        path: '/2.1/info?site=stackoverflow'
    };
    
    https.get(options, function(res) {
      var body = '';
    
      res.pipe(gunzip);
    
      gunzip.on('data', function (data) {
          body += data;
      });
    
      gunzip.on('end', function() {
          console.log(JSON.parse(body));
      });
    });
    

提交回复
热议问题