手把手教你用 Node 搭建一个 Git 服务器

本文用简短的的篇幅教你用 node 搭建一个 git 服务器。 

00 背景

现在 github 支持免费使用私有仓库,所以把代码提交到私有仓库是个不错的选择。 

但是有时候可能会有需求是要部署 git 服务器,或者作为中转 git 服务器。 

01 如何部署

有两个现成的 npm 包可以选择: 

https://github.com/stackdot/NodeJS-Git-Server

https://github.com/gabrielcsapo/node-git-server

下面拿 node-git-server 做一个例子: 

(1)找个服务器,可以用阿里云或者腾讯云服务器, 在服务器上安装 git, 安装 node, pm2。

(2)新建一个目录 git-server , 

mkdir git-server

cd git-server 

npm init -y 

cnpm i node-git-server -S 

touch index.js

(3) index.js 的内容如下 ,

const Server = require('node-git-server');

const path = require('path');

const repos = new Server(path.resolve(__dirname, 'git'), {

    autoCreate: true

});

const port = process.env.PORT || 8080;

repos.on('push', (push) => {

    console.log(`push ${push.repo}/${push.commit} (${push.branch})`);

    push.accept();

});

repos.on('fetch', (fetch) => {

    console.log(`fetch ${fetch.commit}`);

    fetch.accept();

});

repos.listen(port, () => {

    console.log(`node-git-server running at http://localhost:${port}`)

});

(4) 在根目录新建 git 目录,里面放你要建的项目仓库,当然这里可以像 github 一样做个可视化的界面

mkdir git 

cd git 

mkdir 项目名.git 

git init --bare

(5) 到根目录用 pm2 kill, pm2 start index.js 运行起来就可以了。 

(6) {ip}:{端口}/项目名.git 就是你的仓库了。可以 git clone {ip}:{端口}/项目名.git 看看效果。 

更高级的用法可以看文档 https://github.com/gabrielcsapo/node-git-server

转载于:https://www.jianshu.com/p/e8f6700ba6e5

猜你喜欢

转载自blog.csdn.net/weixin_34208185/article/details/91234583