I am trying to use child_process.spawn to call a CLI tool in a for loop with different arguments each time it's called. So far so good, but if I want to introduce a maximum number of the child processes and only continue spawning new processes when a previous process closes, I run into troubles. I wanted to put the for loop in halt with an infinite while loop when the limited child processes amount is achieved. However, the child processes seem to never fire a 'close' event.

Using ls as an example (sorry I can't think of a good, long lasting command that auto quits after a while):

const { spawn } = require("child_process"); const max = 3; let current = 0; // dirsToVisit is an array of paths for (let i = 0; i < dirsToVisit.length; i++) { // if already running 3 ls, wait till one closes while (current >= max) {} current++; lsCommand(dirsToVisit[i]); } function lsCommand(dir) { const ls = spawn("ls", [dir]); ls.on("close", code => { current--; console.log(`Finished with code ${code}`); }); }

This code above never exits, the string to be logged in the console when the child process exits never printed on screen. If I remove the while loop, all child processes finish in the end without issues, but there will be no limit how many processes are allowed at the same time.

Why is my code not working, and how do I correctly limit the number of child process spawned in a loop? Any help would be appreciated!