Run the bash command in Node.js and get the exit code

I can run the bash command in node.js as follows:

var sys = require('sys')
var exec = require('child_process').exec;

function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", function(err, stdout, stderr) {
  console.log(stdout);
});

How to get the exit code of this command ( ls -lain this example)? I tried to work

exec("ls -la", function(err, stdout, stderr) {
  exec("echo $?", function(err, stdout, stderr) {
    console.log(stdout);
  });
});

This somehow always returns 0 regardless of the exit code of the previous command. What am I missing?

+4
source share
3 answers

These two commands run in separate shells.

To get the code, you must be able to check err.codein your callback.

If this does not work, you need to add an event handler exit

eg.

dir = exec("ls -la", function(err, stdout, stderr) {
  if (err) {
    // should have err.code here?  
  }
  console.log(stdout);
});

dir.on('exit', function (code) {
  // exit code is code
});
+12
source

From the docs:

callback, (error, stdout, stderr). error null. error Error. error.code , error.signal , . , 0, .

:

exec('...', function(error, stdout, stderr) {
  if (error) {
    console.log(error.code);
  }
});

.

+2

node :

. Error. error.code , error.signal , . , 0, .

+1

All Articles