Coley G
Coley G

Reputation: 63

Node JS Ongoing Shell Output

I'd like to have Node parse output from an ongoing bash command and do things with it in parallel to the execution of the executed command.

For example,

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

const child = exec('bash server.sh',
  (error, stdout, stderr) => {
    console.log(`stdout: ${stdout}`);
    console.log(`stderr: ${stderr}`);
    if (error !== null) {
      console.log(`exec error: ${error}`);
    }
  });

where server.sh is

yell () {
  echo "bing";
  sleep 1s;
  yell;
}

yell;

The process unfortunately hangs as the execution is waiting for server.sh to finish but it never does. Is there a way to process the output of server.sh as it appears?

Upvotes: 0

Views: 168

Answers (1)

Coley G
Coley G

Reputation: 63

An event listener can be bound like so:

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

Upvotes: 1

Related Questions