我怎么解压缩的NodeJS要求的模块的gzip响应体

2025-04-06 16:27:53
推荐回答(1个)
回答1:

我无法得到请求管用,所以不是结束的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);
});

2. 尝试添加encoding: null给你传递给选项request,这将避免下载体转换为字符串,并保持在一个二进制缓冲区。

3. 这里有一个工作示例(使用节点请求模块)gunzips响应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);
}

全码:

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