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'));
stderr is the default file descriptor where a process can write error messages. Consider this code below: // index.js process. stderr. write("error!
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With