how to run node shelljs in sync mode and get stdout and stderr

CPP picture CPP · May 16, 2016 · Viewed 12.4k times · Source

Within a nodejs script I have the following code which makes the call synchronously and returns the stdout from the shell script I am calling:

var sh = require('shelljs');

... some code
var output = sh.exec('./someshellscript.sh', {silent:true}).stdout;
console.log(output);
... some more code (that shouldnt run until the script is complete)

I can also run the following script which will instead return the stderr:

var sh = require('shelljs');

... some code
var output = sh.exec('./someshellscript.sh', {silent:true}).stderr;
console.log(output);
... some more code (that shouldnt run until the script is complete)

However I want to receive both stdout and stderr in a sync call. Its probably something pretty obvious I am missing herebut I cant work it out.

I think you used to be able run the following command in previous versions but this just returns undefined now:

var sh = require('shelljs');

... some code
var output = sh.exec('./someshellscript.sh', {silent:true}).output;
console.log(output);
... some more code (that shouldnt run until the script is complete)

Relevant software versions are:

  • Ubuntu: 14.04.3 LTS
  • node: 4.4.4
  • npm: 2.15.1
  • shelljs: 0.7.0

Any help appreciated thanks.

Answer

Mauricio Poppe picture Mauricio Poppe · May 17, 2016

From the README for the method exec(command [, options] [, callback])

Executes the given command synchronously, unless otherwise specified. [...], returns an object of the form { code:..., stdout:... , stderr:... }).

Therefore

const { stdout, stderr, code } = sh.exec('./someshellscript.sh', { silent: true })