如何使用request或http模块将gzip页面读入string

我发现js中的请求模块无法正确处理gzip或者扩充格式http响应。

例如:

request({url:'some url'}, function (error, response, body) { //if the content-encoding is gzip, the body param here contains binaries other than readable string. And even worse after you convert the body to buffer, u even can not gunzip it. } 

所以我想在官方文档中使用示例代码。

 var request = http.get({ host: 'izs.me', path: '/', port: 80, headers: { 'accept-encoding': 'gzip,deflate' } }); request.on('response', function(response) { var output = fs.createWriteStream('izs.me_index.html'); switch (response.headers['content-encoding']) { // or, just use zlib.createUnzip() to handle both cases case 'gzip': response.pipe(zlib.createGunzip()).pipe(output); break; case 'deflate': response.pipe(zlib.createInflate()).pipe(output); break; default: response.pipe(output); break; } }); 

问题是代码是写网页到一个文件,我希望它可以写入一个string的页面,以便我可以处理该页面。 我找不到像“StringStream”这样的任何类。

如果有人有任何想法,这将是伟大的。

将响应传递给gzipstream,并像使用原始响应对象一样使用它。

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

简化示例:

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

我遇到了类似的问题,并希望继续使用request库,而不是内置的http模块。 我在这里讨论了两种工作方法: http : //nickfishman.com/post/49533681471/nodejs-http-requests-with-gzip-deflate-compression 。 其中之一与@ Teemu的答案类似,另一个则使用stream。

请求模块处理gzip响应。 我们所要做的就是在opts中设置'gzip'属性。 有关详细说明,请访问下面的链接。 在那里我已经用例子清楚地解释了。

https://stackoverflow.com/a/38582506/5878471

@Dawid和@Teemu的答案在UTF-8编码的情况下,有时会在答案中煞费苦心。 这个代码运行得更好:

 function getGzipped(url, cb) { // downloads gzipped file http.get(url, function(res) { let chunks = []; res.on('data', function(chunk) { chunks.push(chunk); }); res.on('end', function() { let buffer = Buffer.concat(chunks); zlib.gunzip(buffer, function(err, decoded) { if (err) throw err; cb(decoded && decoded.toString()); }); }); }); }