Execute bash command in Node.js and get exit code

Marc Bacvanski picture Marc Bacvanski · Jun 9, 2016 · Viewed 65k times · Source

I can run a bash command in node.js like so:

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 do I get the exit code of that command (ls -la in this example)? I've tried running

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

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

Answer

Joe picture Joe · Jun 9, 2016

Those 2 commands are running in separate shells.

To get the code, you should be able to check err.code in your callback.

If that doesn't work, you need to add an exit event handler

e.g.

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
});