我发现 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;
}
});
问题是代码正在将网页写入文件,我希望它可以将页面写入字符串,以便我可以处理页面。我找不到像'StringStream'这样的类。
如果有人对此有任何想法,那就太好了。