目前我正在使用 chokidar 来观看目录。该目录的文件量很大,并且也在不断地被写入。我还使用轮询,因为我需要监视网络上的文件夹。我注意到当我开始观看目录时,我的 CPU 使用率非常高。
据我了解,还会为目录中的每个文件创建观察者?
我只需要在添加文件时收到通知,不需要监视文件本身的任何更改。所以我觉得为我的需要创造了很多开销。 chokidar 可以以任何方式实现这一点吗?或者我应该寻找另一种解决方案来满足这些需求。
更新: 添加了我如何创建观察者实例的片段。我其实并没有做什么特别的事情。我注意到,一旦创建观察程序,CPU 使用率就会飙升。该目录大约有 20k 个文件。
var fileWatcher = chokidar.watch('path to directory', {
ignored: '*.txt',
ignoreInitial: true,
usePolling: true,
interval: 600,
depth: 0});
fileWatcher.on('add', function(path) {
//Do something when a new file is created in the watched directory
});
最佳答案
所以我找到了一个适合我的解决方案。基本上,如果您需要的只是在目录中创建新文件时收到通知,而不需要监视大目录中的所有文件的所有开销,那么您可以执行类似的操作。
fileWatcher.on('ready', function() {
//Handle anything that need to be done on ready
//At the end of the function unwatch everything in the directory.
//With a large directory this will significantly decrease CPU usage.
});
fileWatcher.on('add', function(path) {
//Do what you need to do when a new file is created
//unwatch this file that was created since we do not care about monitoring it
fileWatcher.unwatch(path);
});
关于javascript - 监视目录中的新文件时 CPU 使用率较高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59691287/