[英]node-metainspetor fetch in Node.js not executing
我在Node.js中有一個簡單的Web抓取腳本,試圖在循環中運行:
var insp = require('node-metainspector');
var client = new insp("http://www.google.com", { timeout: 99999 });
var sleep = require("thread-sleep");
client.on("fetch", function(){
console.log("The title is:");
console.log(client.title);
});
client.on("error", function(err) {
console.log(err);
});
while(true) {
console.log("Checking...");
client.fetch();
sleep(10000);
}
當我在循環外運行client.fetch()
時,它可以很好地工作,但是無論何時在循環中,它都不起作用。 沒有引發任何錯誤(我使用try-catch進行了檢查)。 循環中的其余行將執行。 為什么會發生這種情況,我該如何解決?
thread-sleep
模塊使用同步API( child_process.execFileSync()
)來“睡眠”,這在Node.js中不是推薦的方式。 使用異步API來實現所需的內容更為合適。 在您的情況下,一個簡單的setInterval
可以完成此工作:
var insp = require('node-metainspector');
var client = new insp("http://www.google.com", { timeout: 99999 });
client.on("fetch", function(){
console.log("The title is:");
console.log(client.title);
});
client.on("error", function(err) {
console.log(err);
});
setInterval(function() {
console.log("Checking...");
client.fetch();
}, 10000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.