Search code examples
node.jsstdoutchild-processstderr

Error handling using child_process.execSync in NodeJs


This is my NodeJs snippet:

const {execSync} = require('child_process');
  testoutput = execSync('make test');

Here I am getting stdout as output to testoutput variable from the execSync process if the make process is completely exited. But, if the make test process encounters an stderr error then I am getting an error in NodeJs.

How can I store the stderr message to an output variable testoutput if the make process does not exit and store stdout in variable testoutput if the process exits well with stdout output.


Solution

  • To catch errors with execSync(), you need a try/catch around your call as errors will throw an exception.