title: Limit the number of concurrent child processes spawned in a loop in Node.js
body: <p>I am trying to use <code>child_process.spawn</code> 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.</p>
  
  <p>Using <code>ls</code> as an example (sorry I can't think of a good, long lasting command that auto quits after a while):</p>
  
  <pre><code>const { spawn } = require("child_process");
  
  const max = 3;
  let current = 0;
  
  // dirsToVisit is an array of paths
  for (let i = 0; i &lt; dirsToVisit.length; i++) {
    // if already running 3 ls, wait till one closes
    while (current &gt;= max) {}
    current++;
    lsCommand(dirsToVisit[i]);
  }
  
  function lsCommand(dir) {
    const ls = spawn("ls", [dir]);
    ls.on("close", code =&gt; {
      current--;
      console.log(`Finished with code ${code}`);
    });
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>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!</p>