如果变量移出函数parseUrl,我无法获取值。问题在哪里?
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 []
});
}