[英]Detect file changes in node.js via watchFile
我想检测文件的变化,如果文件发生变化,我会用child_process执行scp命令将文件复制到server.I查找node.js文档,fs.watchFile函数似乎做我想要的做,但当我尝试它,不知何故它只是没有按我的预期工作。 使用以下代码:
var fs = require('fs');
console.log("Watching .bash_profile");
fs.watchFile('/home/test/.bash_profile', function(curr,prev) {
console.log("current mtime: " +curr.mtime);
console.log("previous mtime: "+prev.mtime);
if (curr.mtime == prev.mtime) {
console.log("mtime equal");
} else {
console.log("mtime not equal");
}
});
使用上面的代码,如果我访问监视文件,回调函数得到执行,它将输出相同的mtime,并始终输出“mtime not equal”(我只访问该文件)。 输出:
Watching .bash_profile
current mtime: Mon Sep 27 2010 18:41:27 GMT+0100 (BST)
previous mtime: Mon Sep 27 2010 18:41:27 GMT+0100 (BST)
mtime not equal
任何人都知道为什么if语句失败(也尝试使用===识别检查,但仍然得到相同的输出)当两个mtime是相同的?
如果mtime
属性是Date
对象,那么它们永远不会相等。 在JavaScript中,如果它们实际上是同一个对象(变量指向同一个内存实例),则两个单独的对象是相等的。
obj1 = new Date(2010,09,27);
obj2 = new Date(2010,09,27);
obj3 = obj1; // Objects are passed BY REFERENCE!
obj1 != obj2; // true, different object instances
obj1 == obj3; // true, two variable pointers are set for the same object
obj2 != obj3; // true, different object instances
要检查这两个日期值是否相同,请使用
curr.mtime.getTime() == prev.mtime.getTime();
(我真的不确定是不是这种情况,因为我没有检查watchFile
输出Date对象或字符串,但它绝对看起来像你的描述)
对于“聪明”的人:
if (curr.mtime - prev.mtime) {
// file changed
}
可悲的是,正确的方法是
if (+curr.mtime === +prev.mtime) {}
+强制Date对象为int,即unixtime。
为了简化操作,您可以使用Watchr获取有用的事件(仅在文件实际更改时才会触发change
事件)。 它还支持观看整个目录树:)
我们使用chokidar进行文件监视,甚至可以在运行Windows文件系统的centos机器的可疑环境中运行(在Windows机器上运行的vagrant virtualbox centos)
快速和讨厌的解决方案。 如果您没有按照之前或之后(<或>)进行日期比较,而只是比较日期字符串,只需对每个日期字符串执行快速toString()。
if (curr.mtime.toString() == prev.mtime.toString())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.