Retrieve output as soon as it is displayed in the terminal (Javascript / ShellJS)

Viewed 19

I have a problem, I can't read the output of my shelljs command (which executes java) while the command is running. I don't know if it's clear, but basically I want to have the output of this shelljs command as soon as it appears and not once the java program is finished. Thanks in advance for your answer.

process = shell.exec('exec java.......', {async: true}, function(code, stdout, stderr) {

    //Here I need the output
    console.log('Exit code:', code);
    console.log('Program output:', stdout);
    console.log('Program stderr:', stderr);
});
1 Answers

You need to use spawn instead of exec because spawn emits events while exec simply waits for the execution to complete.

More info: https://nodejs.org/api/all.html#child_process_child_process

const spawn = require('child_process').spawn;

const cmd = spawn('exec java......');

cmd.stdout.on('data', function (data) {
  console.log('Program output:', data.toString());
});

cmd.stderr.on('data', function (data) {
  console.log('Program stderr:', data.toString());
});

cmd.on('exit', function (code) {
  console.log('Exit code:', code.toString());
});
Related