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

前端 未结 5 1326
被撕碎了的回忆
被撕碎了的回忆 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:07

    Pipe the response to the gzip stream and use it as you would use the original response object.

    var req = http.request(options, function(res) {
        var body = "";
    
        res.on('error', function(err) {
           next(err);
        });
    
        var output;
        if( res.headers['content-encoding'] == 'gzip' ) {
          var gzip = zlib.createGunzip();
          res.pipe(gzip);
          output = gzip;
        } else {
          output = res;
        }
    
        output.on('data', function (data) {
           data = data.toString('utf-8');
           body += data;
        });
    
        output.on('end', function() {
            return next(false, body);
        });
     });
    
    req.on('error', function(err) {
       next(err);
    })
    

提交回复
热议问题