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


  • command <string> 运行命令。
  • args <string[]> 字符串参数列表。
  • options <Object>
    • cwd <string> | <URL> 子进程的当前工作目录。
    • input <string> | <Buffer> | <TypedArray> | <DataView> 将作为标准输入传递给生成的进程的值。提供此值将覆盖 stdio[0]
    • argv0 <string> 明确设置发送给子进程的 argv[0] 值。如果未指定,将设置为 command
    • stdio <string> | <Array> 子进程的标准输入输出配置。
    • 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> 来自标准输入输出的结果数组。
    • 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 元字符的输入都可能被用来触发任意命令的执行。