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

anyong3 anyong3 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
应用场景是这样的,我需要在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();

}
}


请问到底要怎么写才能又快又好?
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
anyong3
JavaScript 87,983 成员 224,680 内容