75

リクエストのモジュール応答でgzip圧縮された本文を解凍するにはどうすればよいですか?

Webでいくつかの例を試しましたが、どれも機能していないようです。

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;
                    }
                });
            }
        }
    }
}
4

10 に答える 10

68

私も仕事の依頼が取れなかったので、代わりに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);
});
于 2012-10-08T07:07:32.830 に答える
36

encoding: null渡したオプションに追加してみてくださいrequest。これにより、ダウンロードした本文が文字列に変換されなくなり、バイナリバッファに保持されます。

于 2012-10-11T13:20:30.853 に答える
30

@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);
    }
});
于 2013-09-26T18:20:50.080 に答える
29

実際には、リクエストモジュールが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.
})

注:「応答」イベントで取得したデータはデコードされません。

これは私のために働きます。それがあなたたちにもうまくいくことを願っています。

リクエストモジュールの操作中に通常遭遇する同様の問題は、JSON解析です。説明させてください。リクエストモジュールで本文を自動的に解析し、本文の引数に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
})

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

于 2016-07-26T06:29:49.957 に答える
7

https://gist.github.com/miguelmota/9946206に見られるように:

2017年12月の時点で、requestとrequest-promiseの両方がそのまま処理します。

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)
    }
  )
于 2018-05-02T16:46:41.813 に答える
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
    }
  }

});
于 2014-05-28T02:42:44.553 に答える
4

これが私の2セントの価値です。私は同じ問題を抱えていて、次のようなクールなライブラリを見つけました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());
  }));
于 2016-04-11T14:29:53.237 に答える
3

これは、応答をガンジップする(ノードの要求モジュールを使用する)実際の例です。

function gunzipJSON(response){

    var gunzip = zlib.createGunzip();
    var json = "";

    gunzip.on('data', function(data){
        json += data.toString();
    });

    gunzip.on('end', function(){
        parseJSON(json);
    });

    response.pipe(gunzip);
}

完全なコード:https ://gist.github.com/0xPr0xy/5002984

于 2013-02-21T07:58:22.633 に答える
2

got別の方法として、次のことを簡単に行うことrequestができます。

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

解凍は、必要に応じて自動的に処理されます。

于 2017-05-06T10:41:03.740 に答える
2

node-fetchを使用しています。私が得てresponse.bodyいた、私が本当に欲しかったのはでしたawait response.text()

于 2021-02-13T22:09:19.873 に答える