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?
child_process.spawnSync()
This function exposes the nicest sync interface: https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options
Example:
Output:
Tested in Node.js v10.15.1, Ubuntu 19.10.
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 handlere.g.
From the docs:
So:
Should work.
In node documentation i found this information for the callback function:
On success, error will be null. On error, error will be an instance of Error. The error.code property will be the exit code of the child process while error.signal will be set to the signal that terminated the process. Any exit code other than 0 is considered to be an error.