How to decode gzip or utf-8 response in node?

我是研究僧i 提交于 2019-12-24 03:51:40

问题


I am using node request module to do some get request.I am getting the response body like

{
   body: '\u001f?\b\u0000\u0000\u0000\u0000\u0000...............' 
}

i have the header parameters and request like this,

var params = {
          url: options.url,
          headers: {
                'Accept-Encoding': "gzip, deflate",
                'Accept': '*/*',
                'Accept-Language': 'en-US,en;q=0.5',
                'Accept-Charset' : 'utf-8',
                'Content-Type' : 'application/json',
                 'User-Agent' : 'Mozilla/5.0'
             }
         };

 request(params, function (error, response, body) {   

        //response.setEncoding('utf8');
        //response.setEncoding('binary');

        console.log(response);        
 })

I tried

 //response.setEncoding('utf8');
 //response.setEncoding('binary');

and new Buffer(response.body, 'ascii').toString('utf8') to read the body content but its not working.

how to read the body content properly as JSON ?


回答1:


This works using zlib.createGunzip()

   var http = require("http"),
       zlib = require("zlib");

      var req = http.request(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);
            });
        });

        req.on('error', function (e) {
            callback(e);
        });

        req.end();


来源:https://stackoverflow.com/questions/20636587/how-to-decode-gzip-or-utf-8-response-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!