繁体   English   中英

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

[英]Node.js - unable to save entire output of `git clone` command using child_process spawnSync

我想做的事:

我正在使用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:整个输出都打印到控制台,但我需要将其保存在变量中

另外,我看着inherit的选项options.stdio 尽管它会打印整个结果(而不只是第一行),但我需要将结果保存在变量中。 因此, 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 子进程将整个git clone输出保存在变量中? 到目前为止,我只能打印/显示整个输出(但不能将其保存在变量中)。 另外,我只能在执行git clone命令后保存输出的第一行(而不是整个输出)。

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

根据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}`);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM