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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…