node.js – 访问系统命令的退出代码和stderr

下面显示的代码片段非常适合获取对系统命令的stdout的访问。 有什么方法可以修改此代码,以便还可以访问系统命令的退出代码以及系统命令发送到stderr的任何输出?

#!/usr/bin/node var child_process = require('child_process'); function systemSync(cmd) { return child_process.execSync(cmd).toString(); }; console.log(systemSync('pwd')); 

你不需要做asynchronous。 你可以保留你的execSync函数。

把它包装一下,传递给catch(e)块的Error将包含你正在查找的所有信息。

 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')); 

如果不抛出错误,则:

  • 状态保证为0
  • stdout是函数返回的内容
  • 标准差几乎肯定是空的,因为它是成功的。

在非常非常罕见的事件中,命令行可执行文件返回一个stderr,但以状态0(成功)退出,并且您想要读取它,您将需要asynchronous函数。

你会想要exec的asynchronous/callback版本。 有3个值返回。 最后两个是stdout和stderr。 另外, child_process是一个事件发射器。 听取exit事件。 callback的第一个元素是退出代码。 (从语法上来说,你会希望使用节点4.1.1来获取下面的代码,使其像写入的那样工作)

 const child_process = require("child_process") function systemSync(cmd){ child_process.exec(cmd, (err, stdout, stderr) => { console.log('stdout is:' + stdout) console.log('stderr is:' + stderr) console.log('error is:' + err) }).on('exit', code => console.log('final exit code is', code)) } 

尝试以下操作:

 `systemSync('pwd')` `systemSync('notacommand')` 

你会得到:

 final exit code is 0 stdout is:/ stderr is: 

其次是:

 final exit code is 127 stdout is: stderr is:/bin/sh: 1: notacommand: not found 

你也可以使用child_process.spawnSync() ,因为它返回更多:

 return: 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> The exit code of the child process signal <String> The signal used to kill the child process error <Error> The error object if the child process failed or timed out 

所以你要找的退出代码是ret.status.