Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 543
CPP Avatar asked May 16 '16 21:05

CPP


People also ask

How do I get node output?

Basic output using the console module The most basic and most used method is console. log() , which prints the string you pass to it to the console. If you pass an object, it will render it as a string. const x = 'x'; const y = 'y'; console.

How do I run a shell script in node JS?

Node. js can run shell commands by using the standard child_process module. If we use the exec() function, our command will run and its output will be available to us in a callback. If we use the spawn() module, its output will be available via event listeners.

How do I run an exec in node JS?

The exec() function in Node. js creates a new shell process and executes a command in that shell. The output of the command is kept in a buffer in memory, which you can accept via a callback function passed into exec() .


1 Answers

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 })
like image 179
Mauricio Poppe Avatar answered Oct 21 '22 20:10

Mauricio Poppe