javascript - 查看目录中的新文件时 CPU 使用率高
问题描述
目前我正在使用 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);
});