我在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()时,它运行得非常好,但是只要它在循环中,它就不能工作。没有抛出错误(我检查过了试图捕获)。循环中的其余行执行。为什么会发生这种事,我该怎么解决呢?
发布于 2017-05-07 14:43:08
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);https://stackoverflow.com/questions/43829855
复制相似问题