如何在Nodejs并行进程中运行,但限制当前批量中存在的进程数量?
例如,我有一个包含 200 个项目的数组['word.doc', 'foo.pdf', 'a.txt', ...]
,我需要运行工作流程每个项目如下:
Work.exe word.doc
Work.exe foo.pdf
Work.exe a.txt
Work.exe ....
我所做的是:
- 数组中的
forEach
.. - 从
child_process
lib 调用exec
。
但我每次只想要 5 个进程。当某个进程结束时,一个新项目应该启动并运行。所以每次我只有5个进程,直到所有进程完成。
不知道如何做到这一点。
最佳答案
exec
接受将在子进程退出时调用的回调。您可以轻松地将其与 async 结合起来eachLimit :
const async = require('async');
const child_process = require('child_process');
// items = ['word.doc', 'foo.pdf', 'a.txt', ...]
async.eachLimit(items, 5, (item, done) => {
child_process.exec(`Work.exe ${item}`, done);
});
关于node.js - 如何在有限制的情况下运行并行进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50348483/