2
const {execSync , exec} = require('child_process')
const res = execSync("help")
console.log(res.toString())

For every command I try to execute (in this case 'help') it throws the error "Error: Command Failed .... not found". What I do not understand?

1 Answer 1

7

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.