NodeJS 요청의 모듈 gzip 응답 본문을 어떻게 ungzip (압축 해제)합니까?
요청의 모듈 응답에서 gzip으로 압축 된 본문을 어떻게 압축 해제합니까?
웹에서 몇 가지 예제를 시도했지만 작동하지 않는 것 같습니다.
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;
}
});
}
}
}
}
작업 요청을받을 수 없어서 대신 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);
});
encoding: null
전달하는 옵션에 추가 하십시오 request
. 이렇게하면 다운로드 된 본문을 문자열로 변환하지 않고 바이너리 버퍼에 보관할 수 있습니다.
@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);
}
});
실제로 요청 모듈은 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
https://gist.github.com/miguelmota/9946206 에서 볼 수 있듯이 :
요청 및 요청-약속 모두 2017 년 12 월부터 즉시 처리합니다.
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)
}
)
나는 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
}
}
});
다음은 응답을 건집하는 작업 예제 (노드에 대한 요청 모듈 사용)입니다.
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);
}
Full code: https://gist.github.com/0xPr0xy/5002984
Here is my two cents worth. I had the same problem and found a cool library called 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());
}));
With got
, a request
alternative, you can simply do:
got(url).then(response => {
console.log(response.body);
});
Decompression is handled automagically when needed.
'Program Tip' 카테고리의 다른 글
브라우저 뒤로 버튼으로 되돌아 가면 양식의 모든 필드를 지 웁니다. (0) | 2020.11.26 |
---|---|
속성의 존재를 확인하는 가장 좋은 방법은 무엇입니까? (0) | 2020.11.26 |
If string is not null or empty else에 대한 라이너 1 개 (0) | 2020.11.26 |
사전이 목록보다 훨씬 빠른 이유는 무엇입니까? (0) | 2020.11.26 |
모델을 통해 입력 자리 표시 자의 값을 변경 하시겠습니까? (0) | 2020.11.26 |