NodeJS + jsDom sync calls

I have a quite tricky task, but newbie in NodeJS.

So I need loop over array of URLs, fetch each page from array, pass it thru jsdom+jquery and add new finded URL in the end of array.

On first look task quite simple, but because of Async of NodeJS it's comes to nightmare.

Now I have code like (it's simplified for better understanding)

var jsdom = require("jsdom");
var fs = require("fs");
var jquery = fs.readFileSync("./jquery.js").toString();

var fields = ['http://some.url/page.html']

for(var b=0, len = fields.length;b<len;b++){

jsdom.env({
      html: fields[b],
      src: [jquery],
      done: function (errors, window) {
            var $ = window.$;
            $("div.pager a").each(function() {
                //Push new finded hyperlinks in array
              fields.push($(this).attr('href'));
            });

        }
    });
    //recalculate actual length of array to make more loop
    len=fields.length;
}

and for sure it's construction is not work because of NodeJS concept. Could someone advice how to come it into real live ?

I would clearly suggest you to spent some time and lern asynchronous behavour, it's a power withou it node.js has no sense. The code you pasted is wrong for several reasons.

Plz, take a look of my implementation of links crawler, for pet project I do. Hoe it helps.

https://github.com/alexanderbeletsky/freeze/blob/master/src/crawler.js

You should use async.eachSeries() for this. When you have async code that you need to run in a loop, you should always be using the async library.