Search code examples
node.jschild-process

Managing multiple processes within a NodeJS application


Let's say I'd want to control (start/stop) several other NodeJS scripts from within one "main" NodeJS app. However, not necessarly NodeJS Scripts exclusively, but also simple bash scripts.

I'm looking into the following solution, using execa

// simplified

const managedProcesses = [];

async function Start (pkg) {
  const runningProcess = await execa(pkg.run_command, {
    cwd : pkg.path
  });
  return runningProcess;
}

async function Stop (pkg) {
  // somehow stop the child process
  return
}

const someProcess = await Start({
  run_command : 'node app.js',
  path : './path/to/my/script/'
});

// Keep Reference of process
managedProcesses.push(someProcess);

I first thought pm2 would be a viable solution, but I guess this would only fit for NodeJS-only scripts.

What Problems could I run into using the approach above ?

Should I consider moving forward with this idea ?


Solution

  • For node.js subprocesses there is the cluster module and I strongly recommend using this. For general subprocesses (e.g. bash scripts as you mentioned) you have to use child_process (-> execa). Communication between processes may then be accomplished via grpc. Your approach is fine, so you can consider moving forward with it.