简体   繁体   中英

How to know when all chunks are received

I'm doing https request like this:

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();

The response comes as JSON object, however I get it in my callback as buffer array and in multiple chunks (my callback is called several times). How do I know when all chunks are received? And how then can I convert this array buffer into JSON object?

Answering as requested in the comments.

First thing is wrap your code in another function.

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);
    });
}

And then call the getHttpsData function with a callbackfunction as a parameter.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM