nodejs如何实现一定时间内的文件监控

anyong3 2015-10-21 02:21:00
应用场景是这样的,我需要在30S内监控某个文件是否存在,如果超过30S这个文件还不出现的话就要结束文件监控,继续下一步操作。
一开始我是这样写的:

//监控响应文件

fs.watchFile('d:/out_recv/' + guid + ".rsp", function (curr, prev) {

if (curr.mtime.getTime() !== prev.mtime.getTime()) {

isrsp = true;

fs.unwatchFile('d:/out_recv/' + guid + ".rsp");

response.writeHead(200, { "Content-Type": "text/json" });

fs.readFile('d:/out_recv/' + guid + ".rsp", "utf-8", function (err, data) {

if (!err) {

response.write(data);

response.end();

}
else {

response.write("fail:" + err);

response.end();

}
//删除响应文件
fs.unlink('d:/out_recv/' + guid + ".rsp", function (err) {

if (!err)

console.log('删除响应文件: ' + guid + ".rsq");

else

console.log('删除响应文件出错: ' + err);

});

});

}

});

//创建计时器,30S后停止监控响应文件

setTimeout(function () {

if (!isrsp) {

fs.unwatchFile('d:/out_recv/' + guid + ".rsp");

response.writeHead(200, { "Content-Type": "text/plan" });

response.write("fail:no response json file");

response.end();

}

}, 30000);


但是速度不够快,文件大概1S左右就出现了,但是相应处理大概要4S。

后面我改成这个样子,结果似乎并没有循环直接就退出了。


function watchResponseFile(filePath, num, response) {

if (num < 10) {

fs.exists(filePath, function (exists) {

if (exists) {

fs.readFile(filePath, "utf-8", function (err, data) {

if (!err) {

response.writeHead(200, { "Content-Type": "text/json" });

response.write(data);

response.end();

}

else {

response.writeHead(200, { "Content-Type": "text/json" });

response.write("fail:" + err);

response.end();

}

//删除响应文件

fs.unlink(filePath, function (err) {

});

});

}

else {

num = num + 1;

setTimeout(watchResponseFile(filePath, num, response), 10000);

}

});

}

else {

response.writeHead(200, { "Content-Type": "text/json" });

response.write("fail:no response json file");

response.end();

}
}


请问到底要怎么写才能又快又好?
...全文
149 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
anyong3 2015-10-21
  • 打赏
  • 举报
回复
自己解决了。 setTimeout(watchResponseFile(filePath, num, response), 10000); 改成 setTimeout(function(){watchResponseFile(filePath, num, response);}, 10000); 就好了。

87,909

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧