Run multiple CLI commands inside ONE child process, but HANDLE each output separately in Node

11 Views Asked by At

I need to execute a batch CLI commands inside the only in one child process. For example, suppose i have these shell commands:

echo 1
echo 2
echo 3

As i know, the child_process.exec not really fits in my case because it will create child process per command. I could concatenate these commands via && and run as a shell script via child_process.spawn - but, again, my purpose is to handle each command separately, not just like the whole shell script.

Thanks for any suggestions and tips.

1

There are 1 best solutions below

0
KR1470R On

It turns out that i can send commands to the child_process.spawn process:

const { spawn } = require('child_process');

const shell = spawn('sh');

shell.stdout.on('data', (data) => {
  console.log(data.toString());
});

shell.stderr.on('data', (data) => {
  console.error(data.toString());
});

function sendCommand(command) {
  shell.stdin.write(command + '\n');
}

sendCommand('echo 1');
sendCommand('echo 2');
sendCommand('echo 3');

shell.stdin.end();

That's exactly what i need.