Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js - Accessing the exit code and stderr of a system command

The code snippet shown below works great for obtaining access to the stdout of a system command. Is there some way that I can modify this code so as to also get access to the exit code of the system command and any output that the system command sent to stderr?

#!/usr/bin/node var child_process = require('child_process'); function systemSync(cmd) {   return child_process.execSync(cmd).toString(); }; console.log(systemSync('pwd')); 
like image 570
user3311045 Avatar asked Sep 30 '15 19:09

user3311045


People also ask

What is stderr in node JS?

stderr is the default file descriptor where a process can write error messages. Consider this code below: // index.js process. stderr. write("error!

Which function exits from the current NodeJS process?

exit() method is used to end the process which is running at the same time with an exit code in NodeJS. Parameter: This function accepts single parameter as mentioned above and described below: Code: It can be either 0 or 1.


1 Answers

You do not need to do it Async. You can keep your execSync function.

Wrap it in a try, and the Error passed to the catch(e) block will contain all the information you're looking for.

var child_process = require('child_process');  function systemSync(cmd) {   try {     return child_process.execSync(cmd).toString();   }    catch (error) {     error.status;  // Might be 127 in your example.     error.message; // Holds the message you typically want.     error.stderr;  // Holds the stderr output. Use `.toString()`.     error.stdout;  // Holds the stdout output. Use `.toString()`.   } };  console.log(systemSync('pwd')); 

If an error is NOT thrown, then:

  • status is guaranteed to be 0
  • stdout is what's returned by the function
  • stderr is almost definitely empty because it was successful.

In the rare event the command line executable returns a stderr and yet exits with status 0 (success), and you want to read it, you will need the async function.

like image 105
lance.dolan Avatar answered Sep 21 '22 22:09

lance.dolan