简体   繁体   English

限制使用 nodejs 观看的文件数量

[英]Limit number of file watched with nodejs

I have a script written in nodejs with chokidar where I listen into a folder when a file is added.我有一个用nodejschokidar编写的脚本,当添加文件时,我chokidar在其中监听文件夹。

When a file is added start a function with many loop.添加文件后,启动一个具有许多循环的函数。

Sometimes the system add 100 or more files at the same time so the event add is called 100 times and the server can crash.有时系统会同时添加 100 个或更多文件,因此事件add被调用 100 次,服务器可能会崩溃。

Is there a way to limit watched file and the others wait until watched file are closed?有没有办法限制观看的文件,其他人等到观看的文件关闭?

For example I decide that I can't watch more than 10 files at the same time, the other files wait until first 10 finished their thing.例如,我决定不能同时观看 10 个以上的文件,其他文件要等到前 10 个完成。

Is possible?有可能吗?

This is my script:这是我的脚本:

var chokidar = require('chokidar');
var sys = require('sys')
var exec = require('child_process').exec;

var folder = process.argv[2];
var watcher = chokidar.watch('tmp/xml/' + folder + '/', {ignored: /^\./, persistent: true});
watcher
  .on('add', function(path) {
    var filenameArr = path.split('/');
    filename = folder + '/' + filenameArr[filenameArr.length - 1];

    function puts(error, stdout, stderr) { sys.puts(stdout) }
    exec('bin/cake manager readXmlAndSave ' + filename, puts);
})
const chokidar = require('chokidar');
const async = require("async");

[...]

let taskQueue;
const watcher = chokidar.watch('myPath');
watcher
  .on('add', function(path) {
    taskQueue.push({path});
})

// handle files 10 per 10 to avoid to exhaust critical resources
taskQueue = async.queue(async function(task) {
  await myAsyncHandler(task.path);
}, 10);

taskQueue.error(function(err, task) {
  handleError(err, task);
});

For my culture I'd love to see a pure vanillaJS answer using for example streams and backpressure对于我的文化,我很想看到一个纯粹的 vanillaJS 答案,例如使用流和背压

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM