Ubuntu 12.04
Node v0.6.14
CoffeeScript 1.3.1
fs.watchFile coffee_eval, (e) ->
console.log e
result = spawn 'coffee', ['-bc', coffee_eval]
msg = ''
result.stderr.on 'data', (str) ->
msg+= str
result.stderr.on 'end', ->
console.log 'msg: ', msg
print "!! #{coffee_eval}\n"
Whole code on gist: https://gist.github.com/2621576
Every time I save a file which is watched, the main function is called twitce rather than once.
My Editor is Sumlime Text 2.
the output words can be see :
fs.watchFile is unstable. From the node docs:
fs.watchFile(filename, [options], listener)#
Stability: 2 - Unstable. Use fs.watch instead, if available.
You can try fs.watch
, but unfortunately it may suffer from the same problem. I had the same issue with fs.watch
on windows, when trying to create a similar monitor script.
The workaround was to log the time when the modification occurs and ignore the second change if it was triggered withing a few milliseconds. A bit ugly but it worked.
I would suggest trying node-inotify-plusplus (https://github.com/coolaj86/node-inotify-plusplus) which has worked much better for me than fs.watchFile or fs.watch.
If you are using underscore or lodash, you could consider using throttle and discard the calls on the trailing edge. A basic example would be
var fs = require('fs');
var _ = require("lodash");
function FileWatcher (fileName)
{
this.file = fileName;
this.onChange = _.throttle(this.trigger, 100, {leading: false});
}
FileWatcher.prototype.observe = function ()
{
fs.watch(this.file, this.onChange);
}
FileWatcher.prototype.trigger = function ()
{
console.log("file changed :)");
}
var fileToWatch = __dirname + "/package.json";
new FileWatcher(fileToWatch).observe();
I had the same problem with fs.watch on Windows. The funny thing is that using fs.watchFile (which they recommend against in the docs) worked fine.
To solve this problem, I keep track of the previous "file modified" timestamp and don't run my normal callback code if the value is the same.
var filename = "/path/to/file";
var previousMTime = new Date(0);
var watcher = fs.watch(filename, {
persistent: false
}, function(){
fs.stat(filename, function(err, stats){
if(stats.mtime.valueOf() === previousMTime.valueOf()){
console.log("File Update Callback Stopped (same revision time)");
return;
}
previousMTime = stats.mtime;
// do your interesting stuff down here
});
});