如何从 execSync() 获取 err、stderr?

use*_*178 21 node.js

在节点12中,execSync可以返回stdout,例如

const execSync = require('child_process').execSync;

const stdout = execSync('ls');
console.log(`stdout: ${stdout}`);
Run Code Online (Sandbox Code Playgroud)

但是如何获得 err 和 stderr 呢?在 child_process.exec 的回调中,您拥有全部 3 个。

我可以使用异步方式,但更喜欢使用 execSync() 如果更容易的话。

San*_*tel 16

Nodejs 文档说:

child_process.execSync() 方法通常与 child_process.exec() 相同,但该方法在子进程完全关闭之前不会返回。当遇到超时并发送killSignal时,该方法将不会返回,直到进程完全退出。如果子进程拦截并处理了SIGTERM信号并且没有退出,则父进程将等待,直到子进程退出。

如果进程超时或具有非零退出代码,则此方法将抛出异常。Error 对象将包含 child_process.spawnSync() 的整个结果,如下所示

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.
Run Code Online (Sandbox Code Playgroud)

catch当方法抛出时,上述对象将作为错误对象在块中可用。例如:

const { 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())
}
Run Code Online (Sandbox Code Playgroud)

与spawn方法不同,它不返回子进程实例,而是将stdout结果作为缓冲区返回。另外,检查该方法的stdio选项参数。

工作室| 孩子的 stdio 配置。除非指定了 stdio,否则 stderr 默认情况下将输出到父进程的 stderr。默认值:“管道”。

const { execSync }  = require('child_process');

try {
const result = execSync('ls . *.blah', {
  // stdio: [
  //   0, // Use parent's stdin for child.
  //   0, // use parent's stdout for child.
  //   0, // use parent's stderr for child .
  // ],
});
} catch(err){
  
}

process.stderr.on('data',()=>{
  console.log("stderr",data);
})
Run Code Online (Sandbox Code Playgroud)

  • 这个答案到底在回答什么?我不想抛出或退出“使用非零退出代码”或类似的东西,我只想进入“stderr”。写入“stderr”并以非零值退出是完全独立的活动。 (7认同)

小智 5

execSync 返回: | command.execSync 的标准输出扩展了spawnSync,因此您无法捕获数组错误消息,如果需要,您可以使用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.

Run Code Online (Sandbox Code Playgroud)