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

use*_*045 28 javascript node.js

下面显示的代码片段非常适合访问系统命令的stdout.是否有某种方法可以修改此代码,以便还可以访问系统命令的退出代码以及系统命令发送给stderr的任何输出?

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

lan*_*lan 48

你不需要做Async.您可以保留execSync功能.

在try中包装它,传递给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'));
Run Code Online (Sandbox Code Playgroud)

如果没有抛出错误,那么:

  • 状态保证为0
  • stdout是函数返回的内容
  • stderr几乎肯定是空的,因为它很成功.

在极少数情况下,命令行可执行文件返回一个stderr但退出状态为0(成功),并且您想要读取它,您将需要异步函数.

  • 我会说,进程返回退出代码为0但在stderr中也包含输出实际上很常见.stderr经常用于调试与命令输出无直接关系的信息和其他信息. (3认同)
  • 谢谢lance - 创建了这个npm模块 - shelljs.exec - 它将你在这里放下的所有逻辑包装成一个漂亮的小包 - 欢呼:D (2认同)

bbu*_*123 9

您将需要exec的async/callback版本.返回了3个值.最后两个是stdout和stderr.此外,child_process是一个事件发射器.听取这个exit事件.回调的第一个元素是退出代码.(从语法上看,你会想要使用节点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))
}
Run Code Online (Sandbox Code Playgroud)

请尝试以下方法:

`systemSync('pwd')`

`systemSync('notacommand')`
Run Code Online (Sandbox Code Playgroud)

你会得到:

final exit code is 0
stdout is:/
stderr is:
Run Code Online (Sandbox Code Playgroud)

其次是:

final exit code is 127
stdout is:
stderr is:/bin/sh: 1: notacommand: not found
Run Code Online (Sandbox Code Playgroud)


inf*_*net 6

您也可以使用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
Run Code Online (Sandbox Code Playgroud)

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