I want to detect changes for a file, if the file changes, I will use child_process to execute a scp command to copy the file to a server.I looked up node.js documentation, the fs.watchFile function seems do what I want to do, but when I tried it, somehow it just doesn’t work as I expected. The following code were used:
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");
}
});
With above code, if I access the watched file, the callback function get execute, it will output the same mtime, and always output “mtime not equal” (I only accessing the file). Outputs:
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
Anybody know why the if statement failed(also tried using === identify check, but still get the same output) when the two mtime are the same?
If
mtimeproperties areDateobjects, then these can never be equal. In JavaScript two separate objects are equal ONLY if they are actually the same object (variables are pointing to the same memory instance)To check if these two date values are the same, use
(I’m not actually sure if this is the case since I didn’t check if
watchFileoutputs Date objects or strings but it definitely seems this way from your description)