Question

My app node.js webkit aim to scan each proxy a file.txt and say if the proxy work. But i have a probleme when my for is launch, he don't wait the end of test "http.get" on the line 9. When my first line is tested my var n is on the last line of the file.txt How wait the end of the test line 11 before continue the loop ?

    var file = e.dataTransfer.files[i].path;
    content = fs.readFileSync(file, "UTF-8");
    var lines = content.split("\n");
    for (var n = 0; n < lines.length; n++)
    {
        var arr = lines[n].split(":");

        http.get({host: arr[0], port: arr[1], path: "http://www.google.fr", agent: false}, function(res, req) {
            console.log(req);
            if(res.statusCode == 200){
                el.className = '';
                el.innerHTML = arr[0] + ':' + arr[1] + '\n';
            }
        });
    }
Was it helpful?

Solution 2

You can use a counter in the http.get callback and call it using "bind" to preserve your data in each call.

var file = e.dataTransfer.files[i].path;
content = fs.readFileSync(file, "UTF-8");
var lines = content.split("\n");
var counter = 0;
var callback = function(res, req) {
  console.log(req);
  if(res.statusCode == 200){
    el.className = '';
    el.innerHTML = this[0] + ':' + this[1] + '\n';
  }
  counter++;
  if(counter == lines.length) {
    //do whatever you wanna do after all calls
  }
};
for (var n = 0; n < lines.length; n++){
    var arr = lines[n].split(":");
    http.get({
      host: arr[0], 
      port: arr[1], 
      path: "http://www.google.fr", 
      agent: false
    }, callback.bind(arr));
}

OTHER TIPS

Here is David's answer in detail:

var async = require('async');   // make sure you install async (do "npm install async" from command line)
var file = e.dataTransfer.files[i].path;
content = fs.readFileSync(file, "UTF-8");
var lines = content.split("\n");

async.each(lines, function(line, callback) {
    var arr = line.split(":");

    http.get({host: arr[0], port: arr[1], path: "http://www.google.fr", agent: false}, function(res, req) {
        console.log(req);
        if(res.statusCode == 200){
            el.className = '';
            el.innerHTML = arr[0] + ':' + arr[1] + '\n';
        }
        callback();
    });

},function(){
  console.log("done");
});

I would advice you to take a look at the async.js library. It has a large number of functions to handle the asynchronous nature of javascript. Specifically you would want to use the async.each function.

To give you a bit of an idea take a look at this:

async.each(..., function( file, callback) {
  http.get(...,function(){
   callback();
  });
},function(){
  console.log("done");
});

Or if you want to do one after another use async.eachLimit with a limit of 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top