我想加载一个url并检查页面的所有http和https链接,并将这些链接放入两个不同的文件中。我正在使用javascript,当我尝试在文件中写入所有http url时,仅写入最后一个,而其他未写入。下面是代码
var jsdom = require("jsdom");
var request = require('request');
var fs = require("fs");
jsdom.env(
'http://www.google.com', ["http://code.jquery.com/jquery.js"],
function(error, window) {
console.log("There are", window.$('.body').find('img').length, "img");
var $ = window.$;
$($('.body').find('a')).each(function() {
var src = $(this).attr('href');
if (src.startsWith('http://')) {
console.log(src)
fs.writeFile('out.html', src,
function(err) {
if (err) throw error;
})
}
})
});
如何使这段代码将所有http链接写入out.html文件。现在它只写入最后一个链接。
最佳答案
when I try to write the all the http urls in the file only the last one is written while the others are not written
那是因为您正在使用 fs.writeFile
它会创建一个新文件或用您传递给它的内容覆盖现有文件。
您想要做的是附加到文件中,您可以使用 fs.appendFile
来完成此操作:
fs.appendFile('out.html', src, function(err) {
if (err) {
throw err;
}
});
关于javascript - 如何循环遍历页面的链接并将所有http链接写入java脚本中的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37708807/