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

vit*_*ang 13 javascript 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");
    }   
});
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,如果我访问监视文件,回调函数得到执行,它将输出相同的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
Run Code Online (Sandbox Code Playgroud)

任何人都知道为什么if语句失败(也尝试使用===识别检查,但仍然得到相同的输出)当两个mtime是相同的?

And*_*ris 18

如果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
Run Code Online (Sandbox Code Playgroud)

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

curr.mtime.getTime() == prev.mtime.getTime();
Run Code Online (Sandbox Code Playgroud)

(我实际上不确定是否是这种情况,因为我没有检查watchFile输出Date对象或字符串,但它绝对看起来像你的描述)


CEL*_*CEL 17

对于"聪明"的人:

if (curr.mtime - prev.mtime) {
    // file changed
}
Run Code Online (Sandbox Code Playgroud)

  • @DirkSmaverson减法将日期对象强制转换为数字,就像一元加运算符一样,所以它是等价的. (10认同)

小智 9

可悲的是,正确的方法是

if (+curr.mtime === +prev.mtime) {}
Run Code Online (Sandbox Code Playgroud)

+强制Date对象为int,即unixtime.