我正在做这样的https请求:
var req = https.request(options, function (res) {
console.log('statusCode: ', res.statusCode);
console.log('headers: ', res.headers);
res.on('data', function (d) {
// how to know when all chunks are received
process.stdout.write(d);
});
});
req.end();
响应来自JSON对象,但是我在回调中将它作为缓冲区数组和多个块(我的回调被多次调用)。我怎么知道什么时候收到所有的块?那我怎么能把这个数组缓冲区转换成JSON对象呢?
答案 0 :(得分:2)
根据评论中的要求回答。
首先,将代码包装在另一个函数中。
function getHttpsData(callback){ // pass additional parameter as callback
var req = https.request(options, function (res) {
console.log('statusCode: ', res.statusCode);
console.log('headers: ', res.headers);
var response = '';
res.on('data', function (d) {
// how to know when all chunks are received
//process.stdout.write(d);
response+=d;
});
res.on('end', function(){
var r = JSON.parse(response);
callback(r); // Call the callback so that the data is available outside.
});
});
req.end();
req.on('error', function(){
var r = {message:'Error'}; // you can even set the errors object as r.
callback(r);
});
}
然后使用回调函数作为参数调用getHttpsData
函数。
getHttpsData(function(data){
console.log(data);//data will be whatever you have returned from .on('end') or .on('error')
});