简体   繁体   中英

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?

An event listener can be bound like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM