Node.js-无法使用child_process spawnSync保存git clone命令的全部输出

时间:2019-07-19 20:59:30

标签: node.js git child-process

我想做什么:

我正在使用Node.js通过child_process.spawnSync()执行git clone命令,然后将输出保存在变量中以供以后使用。

示例:

例如,我要执行git clone https://github.com/octo-org/public-repo.git并将结果输出保存在变量中:

Cloning into 'public-repo'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.

失败的尝试1:只能保存输出的第一行(而不是整个输出)

但是,我只能将输出的第一行(即Cloning into 'public-repo'...)保存在变量中。这是我到目前为止的内容:

const args = ["clone", "https://github.com/octo-org/public-repo.git"];
const child = require("child_process").spawnSync("git", args);
const output = `${child.stderr}`;
console.log(output); // only returns "Cloning into 'public-repo'..."

尝试失败2:整个输出都打印到控制台,但是我需要将其保存在变量中

我还研究了options.stdioinherit选项。尽管它会打印整个结果(而不只是第一行),但我需要将结果保存在变量中。因此,options = { stdio: "inherit" }将打印完整的输出,但是我需要将完整的输出保存在变量中。这是我的代码:

// this solution prints the full output
// but i need to save the full output in a variable

const args = ["clone", "https://github.com/octo-org/public-repo.git"];
const options = { stdio: "inherit" };
const child = require("child_process").spawnSync("git", args, options);

尝试失败3:将输出重定向到文件(>)仅写第一行

有人建议将输出重定向到文件(>,但这也只会导致输出的第一行(Cloning into 'public-repo'...)被写入readme.txt文件

require("child_process").exec(
  "git clone https://github.com/octo-org/public-repo.git 2> readme.txt",
  { stdio: "inherit", shell: true },
  (error, stdout, stderror) => {}
);

问题:

如何使用Node.js Child Processes将整个git clone输出保存到变量中?到目前为止,我只能打印/显示整个输出(但不能将其保存在变量中)。另外,在执行git clone命令之后,我只能保存输出的第一行(而不是整个输出)。

1 个答案:

答案 0 :(得分:1)

好的,所以我想出了如何通过将git clone选项传递给--progress(即git clone)来捕获执行git clone --progress <some_remote_url>命令的全部输出。

根据git clone文档,即使stderr流未定向到终端,我们也可以传递--progress选项以强制进度状态。

由于进度状态是针对终端的,并且我正在生成未附加到终端的子进程,所以无法捕获进度输出。

这是更新的Node.js代码传递--progress选项,以捕获git config的全部输出:

// adding --progress works

const args = [
  "clone",
  "https://github.com/octo-org/public-repo.git",
  "--progress"
];
const child = require("child_process").spawnSync("git", args);
console.log(`${child.stderr}`);