通过watchFile检测node.js中的文件更改

我想检测一个文件的变化,如果文件发生变化,我将使用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"); } }); 

使用上面的代码,如果我访问观察文件,callback函数得到执行,它将输出相同的时间,并始终输出“mtime不等于”(我只访问文件)。 输出:

 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中,只有两个独立的对象实际上是相同的对象(variables指向相同的内存实例)

 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 

要检查这两个date值是否相同,请使用

 curr.mtime.getTime() == prev.mtime.getTime(); 

(我不确定是否是这种情况,因为我没有检查watchFile输出Date对象或string,但是从您的描述中看起来确实如此)

对于“聪明”的人:

 if (curr.mtime - prev.mtime) { // file changed } 

可悲的是,正确的方法是

 if (+curr.mtime === +prev.mtime) {} 

+将Date对象强制为int,即unixtime。

为了简化事情,您可以使用Watchr来获取有用的事件(只有在文件实际发生change时才会触发change事件)。 它也支持观看整个目录树:)

我们使用chokidar进行文件监视,即使在运行windows文件系统的centos机器的可疑环境下也是如此(在windows计算机上运行vagrant virtualbox centos)

https://github.com/paulmillr/chokidar

快速和讨厌的解决scheme。 如果你不是以前或之后(<或>)进行date比较,而只是简单地比较datestring,只需在每个string上做一个快速的toString()即可。

  if (curr.mtime.toString() == prev.mtime.toString())