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


  • command <string> 要运行的命令。
  • args <string[]> 字符串参数列表。
  • options <Object>
    • cwd <string> | <URL> 子进程的当前工作目录。
    • input <string> | <Buffer> | <TypedArray> | <DataView> 将作为标准输入传递给生成的进程的值。如果 stdio[0] 设置为 'pipe',提供此值将覆盖 stdio[0]
    • argv0 <string> 明确设置发送给子进程的 argv[0] 的值。如果未指定,将设置为 command
    • stdio <string> | <Array> 子进程的 stdio 配置。参见 child_process.spawn()stdio默认值: 'pipe'
    • env <Object> 环境键值对。默认值: process.env
    • uid <number> 设置进程的用户身份(参见 setuid(2))。
    • gid <number> 设置进程的组标识(参见 setgid(2))。
    • timeout <number> 进程允许运行的最长时间(毫秒)。默认值: undefined
    • killSignal <string> | <integer> 在终止被生成的进程时使用的信号值。默认值: 'SIGTERM'
    • maxBuffer <number> 允许在 stdout 或 stderr 上的最大数据量(以字节为单位)。如果超出,子进程将被终止,任何输出将被截断。请参见 maxBuffer 和 Unicode 的注意事项。 默认值: 1024 * 1024
    • encoding <string> 所有标准输入和输出使用的编码方式。 默认值: 'buffer'
    • shell <boolean> | <string> 如果为 true,将在 shell 中运行 command。在 Unix 上使用 '/bin/sh',在 Windows 上使用 process.env.ComSpec。可以通过字符串指定不同的 shell。参见 Shell 要求默认 Windows shell默认值: false(不使用 shell)。
    • windowsVerbatimArguments <boolean> 在 Windows 上不会对参数进行引号或转义处理。在 Unix 上会被忽略。当 shell 被指定为 CMD 时,该选项会自动设置为 true默认值: false
    • windowsHide <boolean> 隐藏通常在 Windows 系统上创建的子进程控制台窗口。默认值: false
  • 返回:<Object>
    • pid <number> 子进程的 PID。
    • output <Array> 来自 stdio 输出的结果数组。
    • stdout <Buffer> | <string> output[1] 的内容。
    • stderr <Buffer> | <string> output[2] 的内容。
    • status <number> | <null> 子进程的退出码,如果子进程因信号终止,则为 null
    • signal <string> | <null> 用于终止子进程的信号,如果子进程不是因信号而终止,则为 null
    • error <Error> 如果子进程失败或超时,则返回的错误对象。

child_process.spawnSync() 方法通常与 child_process.spawn() 相同,唯一的区别是该函数在子进程完全关闭之前不会返回。当遇到超时并发送 killSignal 时,该方法也不会返回,直到进程完全退出。如果进程拦截并处理了 SIGTERM 信号且没有退出,父进程将等待直到子进程退出。

【The child_process.spawnSync() method is generally identical to child_process.spawn() with the exception that the function will not return until the child process has fully closed. When a timeout has been encountered and killSignal is sent, the method won't return until the process has completely exited. If the process intercepts and handles the SIGTERM signal and doesn't exit, the parent process will wait until the child process has exited.】

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