You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript/Node.js将GitHub仓库A的提交推送到仓库B?

实现GitHub仓库同步的Node.js替代方案

下面几个Node.js包都能帮你实现仓库A的master分支提交后自动同步到仓库B的需求:

1. Git-js

直接调用本地Git命令,功能完整,和原生Git操作逻辑一致,适合需要复杂Git操作的场景。

示例代码:

const git = require('git-js');

// 假设本地已经克隆了仓库A
const repo = git.Repo('/path/to/your/repoA');

async function syncToRepoB() {
  // 拉取仓库A的最新master代码
  await repo.fetch('origin', 'master');
  await repo.checkout('master');
  await repo.pull('origin', 'master');

  // 添加仓库B作为远程(如果还没添加过)
  await repo.addRemote('repoB', 'git@github.com:owner/githubB.git');
  
  // 推送到仓库B的master分支
  await repo.push('repoB', 'master');
}

// 结合Webhook触发(比如收到GitHub的push事件时,先判断是否是master分支的提交)
if (/* 此处替换为你判断master分支提交的逻辑 */) {
  syncToRepoB().catch(err => console.error('同步失败:', err));
}

2. isomorphic-git

纯JavaScript实现的Git,不需要依赖系统安装的Git,跨平台兼容性拉满,尤其适合Serverless这类无法预装Git的环境。

示例代码:

const fs = require('fs');
const git = require('isomorphic-git');
const http = require('isomorphic-git/http/node');

const repoPath = '/path/to/your/repoA';

async function syncToRepoB() {
  // 拉取仓库A的最新master代码
  await git.pull({
    fs,
    http,
    dir: repoPath,
    ref: 'master',
    remote: 'origin',
    auth: process.env.GITHUB_TOKEN // HTTPS方式需要个人访问令牌
  });

  // 添加仓库B作为远程
  await git.addRemote({
    fs,
    dir: repoPath,
    remote: 'repoB',
    url: 'git@github.com:owner/githubB.git'
  });

  // 推送到仓库B,SSH方式需要配置本地密钥,HTTPS方式可以用token
  await git.push({
    fs,
    http,
    dir: repoPath,
    ref: 'master',
    remote: 'repoB',
    // HTTPS认证示例,SSH的话可以忽略这个配置,确保本地密钥有权限访问仓库B
    onAuth: () => ({ username: 'your-github-username', password: process.env.GITHUB_TOKEN })
  });
}

// 触发同步逻辑
if (/* 判断是否是master分支的提交 */) {
  syncToRepoB().catch(err => console.error('同步出错:', err));
}

3. shelljs

通过执行shell命令来操作Git,简单粗暴,适合快速搭起同步逻辑的场景。

示例代码:

const shell = require('shelljs');

// 切换到仓库A的本地目录
shell.cd('/path/to/your/repoA');

function syncToRepoB() {
  // 拉取仓库A最新的master代码
  shell.exec('git pull origin master');

  // 添加仓库B远程(如果已存在就忽略错误)
  shell.exec('git remote add repoB git@github.com:owner/githubB.git || true');

  // 推送到仓库B
  const pushResult = shell.exec('git push repoB master');
  if (pushResult.code !== 0) {
    console.error('同步失败:', pushResult.stderr);
  } else {
    console.log('仓库同步完成');
  }
}

// 当检测到master分支提交时触发
if (/* 替换为你的分支判断逻辑 */) {
  syncToRepoB();
}

另外提一句,你之前用SimpleGit失败大概率是流程有问题——比如你代码里push的是origin(仓库A),根本没指向仓库B;而且也没拉取最新代码就直接push,逻辑不全。不过上面这几个方案都能帮你搞定同步需求。

内容的提问来源于stack exchange,提问作者nb_nb_nb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:50:37