Marc B Marc B - 1 year ago 299
Node.js Question

Execute bash command in Node.js and get exit code

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) {

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) {

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

Joe Joe
Answer Source

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


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

dir.on('exit', function (code) {
  // exit code is code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download