Search code examples
javascriptnode.jsstdoutchild-processstderr

Node.js child_process.exect stdout return null, but stderr did not


Currently, I have this simple code that executes java -version to the command line to check if the user has installed Java.

Odd, that when I run this code, stdout gives me nothing, but stderr gives me my desired result.

cprocess.execSync("java -version", (err, stdout, stderr) => {
  console.log("stdout: " + stdout); // nothing
  console.log("stderr: " + stderr); // output: java version
}

Why is this happening? Do I need to change anything in exec options?


Solution

  • execSync doesn't take a callback argument, but exec does. The text of the question references exec, while the code snippet you shared references execSync, so I'm guessing you meant exec.

    Assuming you really meant to use exec, the callback is correct, and the issue isn't with the code, but the java -version command you're calling - that command outputs the information to stderr, not stdout. You could redirect it, but to be honest, I wouldn't bother - you could just use the stderr output.