为什么 fs.watchFile 在 Node 中调用了两次?

jiy*_*ong 3 node.js

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

要点上的完整代码:https : //gist.github.com/2621576

每次我保存一个被监视的文件时,主函数被称为 twitce 而不是一次。
我的编辑器是 Sumlime Text 2。

输出词可以看到:
在此处输入图片说明

mih*_*hai 6

fs.watchFile 不稳定。来自节点文档:

fs.watchFile(文件名, [选项], 监听器)#

稳定性:2 - 不稳定。如果可用,请改用 fs.watch。

你可以尝试一下fs.watch,但不幸的是它可能会遇到同样的问题。fs.watch当我尝试创建类似的监视器脚本时,我在 Windows 上遇到了同样的问题。

解决方法是记录修改发生的时间,并忽略在几毫秒内触发的第二次更改。有点难看,但它有效。

  • fwiw这些问题在2019年仍然存在 (2认同)

bor*_*mat 5

问题仍然存在,这是我找到的方法。

var actionDone = {}    
fs.watch('.', function(x,filename) {
        var path = './'+filename;
        var stats = fs.statSync(path);
        let seconds = +stats.mtime;
        if(actionDone[filename] == seconds) return;
        actionDone[filename] = seconds
       //write your code here
});
Run Code Online (Sandbox Code Playgroud)

我们在继续之前检查上次修改时间是否不同。