child_process.spawn(command[, args][, options])


  • command <string> 要运行的命令。
  • args <string[]> 字符串参数的列表。
  • options <Object>

    • cwd <string> 子进程的当前工作目录。
    • env <Object> 环境变量的键值对。
    • argv0 <string> 显式设置发送给子进程的 argv[0] 的值。如果没有指定,则设置为 command 的值。
    • stdio <Array> | <string> 子进程的 stdio 配置。参阅 options.stdio
    • detached <boolean> 准备子进程独立于其父进程运行。具体行为取决于平台,参阅 options.detached
    • uid <number> 设置进程的用户标识,参阅 setuid(2)
    • gid <number> 设置进程的群组标识,参阅 setgid(2)
    • shell <boolean> | <string> 如果为 true,则在 shell 中运行 command。 在 UNIX 上使用 '/bin/sh',在 Windows 上使用 process.env.ComSpec。 传入字符串则指定其他 shell。 参阅 shell 的要求Windows 默认的 shell默认值: false(没有 shell)。
    • windowsVerbatimArguments <boolean> 在 Windows 上是否为参数加上引号或转义。在 Unix 上忽略。如果指定了 shell,则自动设为 true默认值: false
    • windowsHide <boolean> 隐藏通常在 Windows 系统上创建的子进程的控制台窗口。默认值: false
  • 返回: <ChildProcess>

child_process.spawn() 方法使用给定的 command 衍生一个新进程,并带上 args 中的命令行参数。 如果省略 args,则其默认为空数组。

如果启用了 shell 选项,则不要将未经过处理的用户输入传给此函数。 包含 shell 元字符的任何输入都可用于触发任意命令执行。

第三个参数可用于指定其他选项,具有以下默认值:

const defaults = {
  cwd: undefined,
  env: process.env
};

使用 cwd 指定衍生进程的工作目录。 如果没有给出,则默认为继承当前工作目录。

使用 env 指定新进程的可见的环境变量,默认为 process.env

env 中的 undefined 值会被忽略。

示例,运行 ls -lh /usr,并捕获 stdoutstderr、以及退出码:

const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`子进程退出码:${code}`);
});

示例,一种非常精细的运行 ps ax | grep ssh 的方式:

const { spawn } = require('child_process');
const ps = spawn('ps', ['ax']);
const grep = spawn('grep', ['ssh']);

ps.stdout.on('data', (data) => {
  grep.stdin.write(data);
});

ps.stderr.on('data', (data) => {
  console.log(`ps stderr: ${data}`);
});

ps.on('close', (code) => {
  if (code !== 0) {
    console.log(`ps 进程的退出码:${code}`);
  }
  grep.stdin.end();
});

grep.stdout.on('data', (data) => {
  console.log(data.toString());
});

grep.stderr.on('data', (data) => {
  console.log(`grep stderr: ${data}`);
});

grep.on('close', (code) => {
  if (code !== 0) {
    console.log(`grep 进程的退出码:${code}`);
  }
});

示例,检查失败的 spawn

const { spawn } = require('child_process');
const subprocess = spawn('bad_command');

subprocess.on('error', (err) => {
  console.log('无法启动子进程');
});

某些平台(macOS、Linux)使用 argv[0] 的值作为进程的标题,其他平台(Windows、SunOS)则使用 command

Node.js 一般会在启动时用 process.execPath 覆盖 argv[0],因此 Node.js 子进程的 process.argv[0] 与从父进程传给 spawnargv0 参数不会匹配,可以使用 process.argv0 属性获取。

  • command <string> The command to run.
  • args <string[]> List of string arguments.
  • options <Object>

    • cwd <string> Current working directory of the child process.
    • env <Object> Environment key-value pairs.
    • argv0 <string> Explicitly set the value of argv[0] sent to the child process. This will be set to command if not specified.
    • stdio <Array> | <string> Child's stdio configuration (see options.stdio).
    • detached <boolean> Prepare child to run independently of its parent process. Specific behavior depends on the platform, see options.detached).
    • uid <number> Sets the user identity of the process (see setuid(2)).
    • gid <number> Sets the group identity of the process (see setgid(2)).
    • shell <boolean> | <string> If true, runs command inside of a shell. Uses '/bin/sh' on UNIX, and process.env.ComSpec on Windows. A different shell can be specified as a string. See Shell Requirements and Default Windows Shell. Default: false (no shell).
    • windowsVerbatimArguments <boolean> No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to true automatically when shell is specified. Default: false.
    • windowsHide <boolean> Hide the subprocess console window that would normally be created on Windows systems. Default: false.
  • Returns: <ChildProcess>

The child_process.spawn() method spawns a new process using the given command, with command line arguments in args. If omitted, args defaults to an empty array.

If the shell option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.

A third argument may be used to specify additional options, with these defaults:

const defaults = {
  cwd: undefined,
  env: process.env
};

Use cwd to specify the working directory from which the process is spawned. If not given, the default is to inherit the current working directory.

Use env to specify environment variables that will be visible to the new process, the default is process.env.

undefined values in env will be ignored.

Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:

const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

Example: A very elaborate way to run ps ax | grep ssh

const { spawn } = require('child_process');
const ps = spawn('ps', ['ax']);
const grep = spawn('grep', ['ssh']);

ps.stdout.on('data', (data) => {
  grep.stdin.write(data);
});

ps.stderr.on('data', (data) => {
  console.log(`ps stderr: ${data}`);
});

ps.on('close', (code) => {
  if (code !== 0) {
    console.log(`ps process exited with code ${code}`);
  }
  grep.stdin.end();
});

grep.stdout.on('data', (data) => {
  console.log(data.toString());
});

grep.stderr.on('data', (data) => {
  console.log(`grep stderr: ${data}`);
});

grep.on('close', (code) => {
  if (code !== 0) {
    console.log(`grep process exited with code ${code}`);
  }
});

Example of checking for failed spawn:

const { spawn } = require('child_process');
const subprocess = spawn('bad_command');

subprocess.on('error', (err) => {
  console.log('Failed to start subprocess.');
});

Certain platforms (macOS, Linux) will use the value of argv[0] for the process title while others (Windows, SunOS) will use command.

Node.js currently overwrites argv[0] with process.execPath on startup, so process.argv[0] in a Node.js child process will not match the argv0 parameter passed to spawn from the parent, retrieve it with the process.argv0 property instead.