What I want to do:
I am using Node.js to execute git clone command using child_process.spawnSync() and then save the output in a variable for later usage.
Example:
For example, I want to execute git clone https://github.com/octo-org/public-repo.git and save the resulting output in a variable:
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.
Failed Attempt 1: only able to save first line of output (not the entire output)
However, I am only able to save the first line of output (i.e., Cloning into 'public-repo'...) in a variable. Here is what I have so far:
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'..."
Failed Attempt 2: entire output is printed to console, but i need to save it in a variable
Also, I looked into inherit option of options.stdio. Although it prints the entire result (instead of just the first line), I need to save the result in a variable. So, options = { stdio: "inherit" } will print the full output, but I need to save the full output in a variable. Here is my code for that:
// 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);
Failed Attempt 3: redirect output to file (>) only writes the first line
Someone suggested redirecting output to file (>), but this also results in only the first line of output (Cloning into 'public-repo'...) being written to readme.txt file
require("child_process").exec(
"git clone https://github.com/octo-org/public-repo.git 2> readme.txt",
{ stdio: "inherit", shell: true },
(error, stdout, stderror) => {}
);
Question:
How can I use Node.js Child Processes to save the entire git clone output in a variable? So far, I am only able to print/display the entire output (but not save it in a variable). Also, I am only able to save the first line of output (but not the entire output) after executing git clone command.
fsand input it into a variable is a better solution?git clone https://github.com/octo-org/public-repo.git > readme.txtgit clone https://github.com/octo-org/public-repo.git > readme.txtusing Node.js Child Processes and it only returns the first line (Cloning into 'public-repo'...). Your suggestion works fine if I manually type the command in the terminal, but not using Node.js child_processgit clone https://github.com/octo-org/public-repo.git 2> readme.txt. Notice I am using2>to redirect to stderr becausegit cloneoutputs to stderr even if status == 0 (i.e. success).