有没有办法在使用 Node.js fs.watch
更改目录内容时仅触发一次?通过更改目录内容,我的意思是从中添加/删除一堆文件?
换句话说,我希望fs.watch
在第一个文件的第一个事件上触发,并忽略特定更改的任何其他事件目录内容循环。
我只能使用 fs.watchFile
来完成此操作,但 Node 人员建议如果可能的话使用 fs.watch
。
Note: fs.watch() is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.
https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener
最佳答案
Yury Tarabanko贵族早些时候回答了这个问题,但不久之后 删除了他的答案:
You simply stop watching on the first call
const watcher = fs.watch(somePath, (ev, file) => { watcher.close() // logic goes here console.log(`${ev} ${file}`) })
在关闭观察者后复活观察者,我们将按照问题中的要求进行 1 次重复行为:
const fs = require('fs')
let dir = './watch1'
function watchOnce()
{
const watcher = fs.watch(dir, (evt, file) => {
watcher.close()
// logic goes here
console.log(Date(), evt, file)
// resurrecting watcher after 1 sec
setTimeout(watchOnce, 1000)
})
}
watchOnce()
Testing
以原始方式创建和删除 10,000 个文件 5 次,中间有 1 秒延迟:
$ for i in {1..5}; do touch {1..10000}; sleep 1; rm {1..10000}; sleep 1; done
验证观察程序恰好触发了 10 次(5 次用于创建 10,000 个文件,5 次用于删除 10,000 个文件):
$ node watchers.js
Wed Jun 07 2017 12:01:44 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:46 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:47 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:49 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:50 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:52 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:53 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:55 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:56 GMT+0300 (EEST) rename 1
Wed Jun 07 2017 12:01:58 GMT+0300 (EEST) rename 1
我不会将我的答案标记为已接受,因为学分主要归于 Yury为了他的 watcher.close()
想法。也许其他人会编写更简洁的解决方案,因为我对在函数中使用延迟并不感兴趣。
关于node.js - 如何使用 fs.watch 每次更改目录内容时触发一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44405877/