我想了用于检测文件更改,如果该文件的变化,我会用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");
    }   
});

使用上面的代码,如果我访问被监视的文件,回调函数得到执行,它会输出相同的修改时间,始终输出“修改时间不等于”(我只访问该文件)。输出:

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) {}

在+力日期对象到INT是unixtime。

要简化事情,你可以使用 Watchr 以获得有用的事件(只会触发change事件如果文件实际上已经改变)。它还支持观看整个目录树:)

我们使用chokidar文件看,其与Windows文件系统运行CentOS的机器的可疑情况下工作,甚至(在Windows机器上运行的流浪汉VirtualBox的CentOS的)

https://github.com/paulmillr/chokidar

快速和讨厌的溶液。 如果你没有做在以前或以后条款的日期比较(<或>),你只是比较datestrings,只是做一个快速的toString()上的每一个。

 if (curr.mtime.toString() == prev.mtime.toString()) 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top