How do I receive stderr with the return value of child_process.execSync (command[, options]) in node.js(v4.3.2)
node.js
If you need stderr
, for example, you should use spawnSync
.
The following is an example of overdoing it with execSync
.
The main method is to bring the error output to the standard output by attaching 2>>1
to the command.
This is a shell function, so if you want to know more about it, please look into shell and shell scripts, not node.js
.
Assume sh-like shells.
#!/usr/bin/node
"use strict";
varchild_process=require("child_process");
console.log("#Retrieved by redirecting to standard output.Mix with standard output";
// The last thing I'm doing is running the true command to make sure it's successful.
varls_stdout_and_err =child_process.execSync("ls exist.txt not_exist.txt2>&1;true");
console.log({ls_stdout_and_err:ls_stdout_and_err.toString()});
console.log("\n#Retrieved by redirecting to standard output.Discard the original standard output.");
varls_stderr =child_process.execSync(
"ls exist.txt not_exist.txt2>&1>/dev/null;true";
console.log({ls_stderr:ls_stderr.toString()});
console.log("\n#Replace standard output with errors");
varls_stderr =child_process.execSync(
"ls exist.txt not_exist.txt3>&1>&22>&3;true";
console.log({ls_stderr:ls_stderr.toString()});
console.log("\n#Retrieve by catching errors";
try{
// The last time I'm running the false command is to make sure it fails.
child_process.execSync("ls exist.txt not_exist.txt; false");
}
catch(err){
console.log({
ls_stdout —err.stdout.toString(),
ls_stderr —err.stderr.toString(),
});
}
If you run it on a terminal, for example:Note that the error output of the command is also displayed.
#Retrieved by redirecting to standard output.be mixed with standard output
{ ls_stdout_and_err: 'ls:cannot access\'not_exist.txt\': No such file or directory\nexist.txt\n'}
# Retrieved by redirecting to standard output.discard the original standard output
{ ls_stderr: 'ls:cannot access\'not_exist.txt\': No such file or directory\n'}
# Obtain standard output and error replacement
exist.txt
{ ls_stderr: 'ls:cannot access\'not_exist.txt\': No such file or directory\n'}
# Retrieving by Error Catch
ls:cannot access 'not_exist.txt'—No such file or directory
{ ls_stdout: 'exist.txt\n',
ls_stderr: 'ls:cannot access\'not_exist.txt\': No such file or directory\n'}
© 2024 OneMinuteCode. All rights reserved.