chriskelly chriskelly - 3 years ago 249
Node.js Question

child_process not returning correct exit code from batch file

I'm trying to get the correct exit code from a batchfile using nodejs on Windows.

When run from the command line I see the expected error code:

ml.bat profile bootstrap

ERROR: [".../deploy/lib/RoxyHttp.rb:362:in
block in request'", ".../deploy/lib/RoxyHttp.rb:352:in
loop'", ".../deploy/lib/RoxyHttp.rb:352:in
request'", ".../deploy/lib/MLClient.rb:110:in
go'", ".../deploy/lib/server_config.rb:1963:in
get_sid'", ".../deploy/lib/server_config.rb:2056:in
bootstrap'", "deploy/lib/ml.rb:168:in `'"

I verify that there exit code was non-zero:

echo %errorlevel%


Below is the correspoinding code I use in NodeJS - which always gives an exit code of 0:

var stdout = "";
let proc = child_process.spawn("ml.bat", ["profile", "bootstrap"], {shell:true});

proc.stdout.on('data', d => stdout += d.toString() + '\n';);
proc.on('close', exitcode => {

if (exitcode !== 0) {
console.log('ERROR in command');

I have tried using several variations (exec, execSync, spawnSync) and options (shell, "cmd.exe /c") but I can never get a non-zero code using node. The program does not print any output on stderr.

Any idea how to get back the right error code in NodeJS?

Answer Source

To solve the problem, I added the following last line to ml.bat:

exit /b %errorlevel%

Now it behaves identically on both windows and linux.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download