In node 12, execSync can return stdout, e.g.
const execSync = require('child_process').execSync;
const stdout = execSync('ls');
console.log(`stdout: ${stdout}`);
But how to get err and stderr ? In the callback of child_process.exec, you have all 3.
I can use async way, but prefer to use execSync() if it's easier.
Nodejs docs says:
The child_process.execSync() method is generally identical to child_process.exec() with the exception that the method will not return until the child process has fully closed. When a timeout has been encountered and killSignal is sent, the method won't return until the process has completely exited. If the child process intercepts and handles the SIGTERM signal and doesn't exit, the parent process will wait until the child process has exited.
If the process times out or has a non-zero exit code, this method will throw. The Error object will contain the entire result from child_process.spawnSync() as below
Returns: <Object>
pid <number> Pid of the child process.
output <Array> Array of results from stdio output.
stdout <Buffer> | <string> The contents of output[1].
stderr <Buffer> | <string> The contents of output[2].
status <number> | <null> The exit code of the subprocess, or null if the subprocess terminated due to a signal.
signal <string> | <null> The signal used to kill the subprocess, or null if the subprocess did not terminate due to a signal.
error <Error> The error object if the child process failed or timed out.
So I think using a try-catch
would work. When method throw, the above object will be available in catch
block as error object. Try to run this code snippet in replit
let {execSync}= require('child_process');
try {
let res= execSync('ps')
console.log("NO ERROR")
console.log(res.toString())
}
catch (err){
console.log("output",err)
console.log("sdterr",err.stderr.toString())
}
https://repl.it/repls/GlamorousMistyElements
execSync Returns: | The stdout from the command.execSync extents spawnSync, so you cannot catch array error message, if you want, you can use spawnSync, https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options
Returns: <Object>
pid <number> Pid of the child process.
output <Array> Array of results from stdio output.
stdout <Buffer> | <string> The contents of output[1].
stderr <Buffer> | <string> The contents of output[2].
status <number> | <null> The exit code of the subprocess, or null if the subprocess terminated due to a signal.
signal <string> | <null> The signal used to kill the subprocess, or null if the subprocess did not terminate due to a signal.
error <Error> The error object if the child process failed or timed out.
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