2

Thank you for taking the time to read my question!

I'm new to Node.js and I'm trying to figure out how to output the elements of an array to the console when a server response has come to an end.

This is the code:

var http = require('http');

http.get(process.argv[2], function (response) {
    response = response.setEncoding('utf8');
    var data = [];

    response.on('data', function (collect) {
        data.push(collect);
    });

    response.on('error', function(err) {
        console.log(err);
    });

}); 

Where and how do I use response.end event to print out all of the elements of the data array using console.log() method?

Thank you very much for your help!

4
  • You'd just add it anywhere inside the callback, did you try something ? Commented Nov 13, 2016 at 19:30
  • I tried response.end(function() { for (var i = 0; i < data.length; i++) { console.log(data[i]); } }); but it does not work as response.end is not a function. Commented Nov 13, 2016 at 19:35
  • 1
    Use response.on('end',, also since the chunks (yours collect) is string it would make sence to do data += collect instead of push this assumes you define data as string var data = ''; Commented Nov 13, 2016 at 19:42
  • @Molda Thank you for pointing that out! Makes it much more efficient and elegant! Commented Nov 13, 2016 at 19:46

1 Answer 1

1

The answer was staring me right in the face! I didn't need to call the response.end method, instead i needed to call the response.on method and pass it the end event.

Here is what worked for me:

response.on('end',function(){
        for (var i = 0; i < data.length; i++) {
            console.log(data[i]);
        }
    });

Full code:

var http = require('http');

http.get(process.argv[2], function (response) {
    response = response.setEncoding('utf8');
    var data = [];

    response.on('data', function (collect) {
        data.push(collect);
    });

    response.on('error', function(err) {
        console.log(err);
    });

    response.on('end',function(){
        for (var i = 0; i < data.length; i++) {
            console.log(data[i]);
        }
    });

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.