简体   繁体   中英

Pass variable to nodejs function

I have simple nodejs function that should work as follow:

  1. Making GET request to list of urls.
  2. Collecting all responses to array.
  3. Print responses line by line.

Problem is that I initialize results array at start and in middle of function I am pushing response strings to this array, but at the end this array is empty.

var http = require('http');
var bl = require('bl');
var argv = process.argv;
var results = [];

    for (i = 2; i < argv.length; i++) {
    var url = argv[i].toString();
    http.get(url, function (response) {
        response.pipe(bl(function (err, data) {
            results.push(data.toString());  //if im just printing the data it shows the correct info.
        }))
    })

}
console.log(results);

So response is just "[]".

As pointed out in the comments, http.get works asynchronously. Therefore you have to work with its events to populate your array and wait until all of them have finished to print out the result.

You could take this as an example (not going to use bl):

var http = require('http');
var argv = process.argv;
var results = [];

for (i = 2; i < argv.length; i++) {
    var url = argv[i].toString();
    http.get(url, function (response) {
        var res = '';
        response.setEncoding('utf8');

        response.on('data', function (data) {// Collect data.
            res += data;
        });

        response.on('end', function () {// Response's finished, print out array if we have collected all the requests.
            results.push(res);
            if (results.length === argv.length - 2) {
                console.log(results);
            }
        });
        response.on('error', console.log);
    });

}
//console.log(results);// This is not correct as it'll print out an empty array due to the asynchrous nature of http.get

Hope it helps.

Here http.get is working asynchronously. So Try promise

        var http = require('http');
        var bl = require('bl');
        var argv = process.argv;
        var defer = require("promise").defer;
        var deferred = defer();
        var results = [];

            for (i = 2; i < argv.length; i++) {
            var url = argv[i].toString();
            http.get(url, function (response) {
                response.pipe(bl(function (err, data) {
                    results.push(data.toString());  //if im just printing the data it shows the correct info.

                }));
                deferred.resolve("succesful result");
            });
        }

       deferred.promise.then(function(result){
           console.log(results);
       },
       function(error){
          //... executed when the promise fails
       });

It works for me.

Thank you all for your responses, thay are working, but I found answer with "bl".

var http = require('http');
var bl = require('bl');
var argv = process.argv;
var results = []

function printResults() {
    for (var i = 2; i < argv.length; i++)
        console.log(results[i])
}


for (i = 2; i < argv.length; i++) {
    var url = argv[i].toString();
    http.get(url, function (responce) {
        responce.pipe(bl(function (err, data) {
            results[i] = data.toString()
            if (count == 3) {
                printResults()
            }
        }))
    })
}

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