适用范围:

1. 缺点:

  1. 每一次执行命令, 都会新建一个进程
  2. 切换了目录之后, 进程立马就关闭了, 不能影响后面命令的工作目录

梗概:

  1. 如果提供了回调函数, 则会截取命令向终端的输出, 并传递给回调函数
  2. 原生的exec是非promise的回调型异步函数
  3. 每次exec都会单独开辟一个进程去运行shell命令

语法:

1. 异步版本:

child_process.exec("shell命令"[, 参数选项][, 回调函数])

2. 同步版本:

child_process.execSync("shell命令"[, 参数选项])

3. 参数说明:

3.1. 参数选项

  • cwd <string> | <URL> 子进程的开始目录
    • 默认: process.cwd().
  • env <Object> Environment key-value pairs.
    • 默认: process.env.
  • input <string> | <Buffer> | <TypedArray> | <DataView> 输入给该进程的输入值
    • Supplying this value will override stdio[0].
    • 同步才有的参数
  • stdio <string> | <Array> Child’s stdio configuration. stderr by default will be output to the parent process’ stderr unless stdio is specified.
    • 默认: ‘pipe’.
    • 同步才有的参数
  • encoding <string> 如果设置了, 传给回调函数的stdout就是字符串, 否则为buffer类型
    • 默认: ‘utf8’
  • shell <string> 运行shell命令的shell程序
    • 默认: ‘/bin/sh’ on Unix, process.env.ComSpec on Windows.
  • signal <AbortSignal> allows aborting the child process using an AbortSignal.
  • timeout <number> 默认: 0
  • maxBuffer <number> 如果返回值为buffer时, buffer的最大值
    • 默认: 1024 * 1024.
  • killSignal <string> | <integer> 默认: ‘SIGTERM’
  • uid <number>
    • Sets the user identity of the process (see setuid(2)).
  • gid <number>
    • Sets the group identity of the process (see setgid(2)).
  • windowsHide <boolean> 是否隐藏shell程序的窗口
    • 默认: false.

3.2. 回调函数:

回调函数接受三个参数: error, stdout, stderr

2. 传给回调函数的error类型

interface ExecException extends Error {
	cmd?: string | undefined;//shell命令
	killed?: boolean | undefined;
	code?: number | undefined;//命令的返回值,非零都是错误
	signal?: NodeJS.Signals | undefined;
}

更具体的api文档, 可以查看@types/node下的有关声明

4. 返回值:

  1. 异步下, 返回child_process
  2. 同步下, 返回命令输出的string或buffer

2. 实例:

var exec = require('child_process').exec;
var child = exec('echo hello ', function(err, stdout, stderr) {
  if (err) throw err;
  console.log(stdout);
});