Javascript 如何知道何时收到所有块

Javascript 如何知道何时收到所有块,javascript,node.js,Javascript,Node.js,我正在这样做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

我正在这样做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对象呢?

按照注释中的要求进行应答

首先,将代码包装到另一个函数中

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);
    });
}
然后使用callbackfunction作为参数调用
getHttpsData
函数

getHttpsData(function(data){
    console.log(data);//data will be whatever you have returned from .on('end') or .on('error')
});

res.on('end',废话)
?谢谢,您是否建议我将
data
callback上的所有数据写入某个变量,然后在
end
callback上,我将该变量的数组缓冲区转换为json?这将是最首选的方式,除非您有一些必须将数据逐块放入stdout的要求。:)另外,使用回调函数作为参数,然后使用接收到的数据在
.on('end')
中调用该回调函数也是一种很好的做法。谢谢,您能否提供代码,因为您最后的建议是使用回调函数的一种很好的做法?那我就接受答案了。您能告诉我您的代码中有什么
https
?它是一个简单的
require('https')
,还是
require(
request
的别名,还是其他什么东西,尽管我建议a)遵循
节点
约定,使用单独的
成功
错误
回调函数,或者我跳过回调,改用承诺。@JeremyJStarcher:谢谢!我将更新答案以反映这些情况。:)