Dive in NodeJs child process module
I decided to look at NodeJS source code at here to understand the problem. execSync method use spawnSync to run the command, and in the end, it calls checkExecSyncError. In the latter, you can see that if the status code is not 0, it will throw the error "Command failed ...".
Then I try to run const res = spawnSync("help");, and res.status gives me 1. So, the command help actually yields an "invisible" error although we can see the expected output on the terminal.
Note: Exit status 1 is the catch-all for general error, AFAIK. Exit status 0 means success. Further reading
Confirm in the terminal
I go to my terminal to confirm this, I ran help then echo %ERRORLEVEL%. (thank Tim Gilbert) and I received 1. So it totally makes sense for me.
Even the command throws an error, we can still get the output in this case. You can refer to my code below:
const { execSync } = require('child_process')
console.log(process.env.ComSpec);// verify what terminal is used
try {
// success command
const resNpmVersion = execSync("npm -v");
console.log("success", resNpmVersion.toString());
// failed command, the result is printed in the catch block
const resHelp = execSync("HELP");
} catch (error) {
console.log(error.message);
console.log("error", error.stdout.toString());
}
Lesson learned: Check the exit status of the command :)
(I did my test on Windows 10)