1

I can not get the value if the variable was moved out of the function parseUrl. Where is the problem?

var request = require('request');
var cheerio = require('cheerio');
var dir = [];

var url = 'http://google.com/';
parseUrl(url);
function parseUrl (url) {
  request(url, function (err, resp, body) {
    var $ = cheerio.load(body);
    var items = [];
      var dir = [];
    $('a').each(function (k, v) {
      items.push({
        title: $(this).text(),
        href: $(this).attr('href')
      });
    });
    items.forEach(function (k, v) {
      if (k.href[k.href.length-1] == '/') {
        dir.push(k);
      }
    });
    console.log(dir); <---- if I move this line to the outside of function parseUrl, then I got an empty array []
  });
}
Hao Wang
  • 135
  • 2
  • 4

0 Answers0