如何使用Node.js克隆GitHub存储库

13

我需要一种可靠的方式使用Node.js和必要的npm包克隆GitHub仓库并将其粘贴到本地目录中。

这段代码正在使用nodegit库,但无法克隆GitHub仓库。它创建了一个名为.git的单个文件夹,并未复制任何来自仓库的文件。我尝试了几个库,其中大部分都有非常复杂的代码或不起作用。这之前是可以正常工作的,但现在不行了(它随心所欲地开关)。请帮忙找到一份可靠的代码,从URL克隆GitHub仓库并将其粘贴到本地目录中。谢谢。

var nodegit = require('nodegit'),
    path = require('path');

var url = "https://github.com/atomicptr/dauntless-builder", //also tried https://github.com/atomicptr/dauntless-builder.git
    local = "C:/data",
    cloneOpts = {};

nodegit.Clone(url, local, cloneOpts).then(function (repo) {
    console.log("cloning succesful!");
    console.log("Cloned " + path.basename(url) + " to " + repo.workdir());
}).catch(function (err) {
    console.log(err);
});

这段代码没有错误,但实际上无法克隆存储库。


如果您不关心用户是否安装了 git,您可以使用 child_processexec 方法来执行命令。 - Adam Kosmala
你已经尝试过使用 GitHub API 或者 nodegit了吗? - AZ_
3个回答

21
你可以使用 shelljs 来实现此操作。
const shell = require('shelljs')
const path = 'absolute/path/to/folder'
shell.cd(path)
shell.exec('git clone https://github.com/atomicptr/dauntless-builder')

谢谢 :) 也有一种方法可以将本地机器上的文件上传到我的Github仓库吗?如果可以,你能告诉我吗?我发现很难让任何代码工作。 - Siddharth Agrawal
是的,你可以在ShellJS中使用任何终端命令。例如,你可以添加 shell.cd('dauntless-builder') 然后执行 shell.exec('git push') - Jasper Bernales
要使用GitHub,您不需要通过git进行操作,当然也不需要使用CLI命令。此外,未经授权的情况下,git push无法正常工作。您需要首先使用git config设置配置。 - AZ_
@AZ_ 你反对使用命令行界面来访问Git仓库吗? - Emobe

8
假设你已经在计算机上安装了 git,那么你只需要在节点中运行 clone 命令即可。
const path = require('path');
const{ execSync } = require('child_process');

execSync('git clone repolink', {
  stdio: [0, 1, 2], // we need this so node will print the command output
  cwd: path.resolve(__dirname, ''), // path to where you want to save the file
})

谢谢 :) 也有一种方法可以将本地机器上的文件上传到我的Github仓库吗?如果可以,你能告诉我吗?我发现很难让任何代码工作。 - Siddharth Agrawal
如果您使用SSH而不是HTTPS克隆存储库,并正确设置了您的SSH密钥,则应该可以使用git push。 - robi932
这是理想的解决方案,因为它不需要npm包。它还很有用,因为它使用execSync,似乎这是从节点克隆git的唯一方法,而不会使进程挂起,异步exec例如永远不会触发回调。 - Shukri Adams
@ShukriAdams 你有关于异步执行问题的链接吗? - UpTheCreek

5

尝试使用git-clone npm包

npm i git-clone

var clone = require('git-clone');

clone(repo, targetPath, [options], cb);

支持的选项:

git:git二进制文件路径;默认值:git(可选)。

shallow:当为true时,使用深度1进行克隆(可选)。

checkout:要检查的修订版/分支/标签(可选)。


虽然它提供的选项非常有限,但使用起来还是不错的。 - Zain Ul Abidin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接