Use the async package and it executes the function: eachLimit
it does the same as lodash , but with asynchronous stream processing and expiration of the iterations at the same time:
var async = require('async'); var exec = require('child_process').exec; var folders = [...]; // a list from somewhere var maxProcesses = 5; // 5 items at a time async.eachLimit( folders, // collection maxProcesses, // limit function(folder, next) { // iterator function. args: item, callback var cmd = "tar -cf " + folder + ".tgz " + folder; console.log('calling:', cmd); exec(cmd, function(err, stdOut, stdErr) { // executing cmd if(err) console.error(err); // if error putting to console next(); // passing the async flow to handle the next iteration }); }, function() { // after all iterations finished console.log('finished processing commands'); });
or parallelLimit :
var async = require('async'); var _ = require('lodash'); var exec = require('child_process').exec; var folders = [...]; // a list from somewhere var callStack = []; _.each(folders, function(folder) { // generating our stack of commands callStack.push(function(done) { var cmd = "tar -cf " + folder + ".tgz " + folder; exec(cmd, function(err, stdOut, stdErr) { if(err) console.error(err); done(null, folder); }); }); }); var maxProcesses = 5; // 5 items at a time async.parallelLimit(callStack, maxProcesses, function() {console.log('finished');});
"making it look shorter" :)
const async = require('async'), exec = require('child_process').exec; let folders = [...]; async.eachLimit(folders, 5, (folder, next) => exec("tar -cf " + folder + ".tgz " + folder, () => next()), () => console.log('finished'));
and
const async = require('async'), exec = require('child_process').exec; let folders = [...]; let commands = folders.map(folder => done => exec("tar -cf " + folder + ".tgz " + folder, () => done()); async.parallelLimit(commands, 5, () => console.log('finished'));
if any of these examples is not suitable for you or your system is very large, so try using a message queuing system like rsmq