无法从 Windows 上的 Node.js 脚本生成 `gcloud app deploy`

Can't spawn `gcloud app deploy` from a Node.js script on Windows

我正在构建一个 Electron 应用程序 (Node.js),它需要从具有实时反馈的应用程序 (stdin/stdout/stderr) 中生成 gcloud app deploy

我迅速从 child_process 切换到 execa,因为我在 Mac OS X 上遇到一些问题,child_process 缓冲区限制为 200kb (并且 gcloud app deploy 发送了一些大于 200kb 的大字符串,导致命令崩溃)。

现在,execa 在 OSX 上似乎一切正常,但在 Windows.

上似乎一切正常

代码看起来像这样:

let bin = `gcloud${/^win/.test(process.platform) ? '.cmd' : ''}`

//which: https://github.com/npm/node-which
which(bin, (err, fullpath) => {
  let proc = execa(fullpath, ['app', 'deploy'], {
    cwd: appPath
  })
  proc.stdout.on('data', data => {
    parseDeploy(data.toString())
  })
  proc.stderr.on('data', data => {
    parseDeploy(data.toString())
  })
  proc.then(() => {
    ...
  }).catch(e => {
    ...
  })
})

此代码在 Mac OS X 上完美运行,而我在 Windows

上没有相同的结果

我尝试了很多东西:

我制作了一个 GIST 来显示我在 Windows 上使用基本子进程脚本进行的一些测试得到的响应: https://gist.github.com/thyb/9b53b65c25cd964bbe962d8a9754e31f

我还在 execa 存储库上开了一个问题:https://github.com/sindresorhus/execa/issues/97

有人遇到过这个问题吗?我四处搜索,发现除了这个 reddit thread 没有解决这个问题之外没有任何希望。

在幕后,gcloud.cmd 是 运行 一个 python 脚本。在阅读了大量关于 ChildProcess / Python 和 Windows 的 Node.js 问题后,我陷入了这个话题:https://github.com/nodejs/node-v0.x-archive/issues/8298

Node.js 子进程中的 运行 Python 脚本存在一些已知问题。 他们在这个 comment 中讨论了 python 的无缓冲选项。通过添加 -u 选项更新 gcloud.cmd 中的 shell 脚本后,我注意到一切都按预期工作

这个comment explains how to set this option as an environment variable (to not modify the windows shell script directly): https://docs.python.org/2/using/cmdline.html#envvar-PYTHONUNBUFFERED

因此将 PYTHONUNBUFFERED 添加到环境变量中可以解决此问题!

execa(fullpath, ['app', 'deploy'], {
  cwd: appPath,
  env: Object.assign({}, process.env, {
    PYTHONUNBUFFERED: true
  })
})