【问题标题】:How to clone github repo using node.js如何使用 node.js 克隆 github 存储库
【发布时间】:2019-12-31 07:14:57
【问题描述】:

我需要一种可靠的方法来克隆 github 存储库并使用 node.js 和任何必要的 npm 包将其粘贴到本地目录中。

此代码使用 nodegit 库,无法克隆 github 存储库。它会创建一个名为 .git 的文件夹,并且不会从 repo 中复制任何文件。我已经尝试了几个库,其中大多数都有非常复杂的代码或不起作用。这以前有效,但现在不行。 (它随心所欲地打开和关闭)。请帮助,我需要一个可靠的代码,从 url 克隆一个 github repo 并将其粘贴到本地目录中。谢谢。

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);
});

此代码未显示任何错误,但实际上无法克隆 repo。

【问题讨论】:

  • 如果你不关心用户是否安装了git,你可以解决使用child_processexec方法来执行命令
  • 您是否尝试过使用GitHub API's?或nodegit.

标签: javascript node.js git github clone


【解决方案1】:

您可以为此使用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 存储库吗?如果是的话,你能告诉我吗?我发现很难让任何代码正常工作。
  • 是的。您可以在 shelljs 的终端中执行任何命令。对于这个例子,你可以添加shell.cd('dauntless-builder') 然后,shell.exec('git push')
  • 要使用 GitHub,您不需要通过 git,当然也不需要 CLI 命令。此外, git push 未经授权将无法工作。您需要先使用 git config 设置配置。
  • @AZ_ 你反对使用 CLI 访问 git repos??
【解决方案2】:

假设你在机器上安装了 git,你可以简单地从节点运行克隆命令。

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 存储库吗?如果是的话,你能告诉我吗?我发现很难让任何代码正常工作。
  • 如果您使用 ssh 而不是 https 克隆 repo,并且您正确设置了 ssh 密钥,它应该与 git push 一起使用
  • 这是理想的解决方案,因为它不需要 npm 包。它也很有用,因为它使用 execSync,这似乎是从节点 git clone 而不挂起进程的唯一方法,async exec f.ex 永远不会触发回调。
  • @ShukriAdams 你有关于异步执行问题的链接吗?
【解决方案3】:

试试git-clone npm 包

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

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

支持的选项:

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

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

结帐:要结帐的修订/分支/标签(可选)。

【讨论】:

  • 虽然它提供的选项非常有限。但是很好用
猜你喜欢
  • 2020-03-25
  • 2021-12-31
  • 2021-11-18
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
相关资源
最近更新 更多