MENU

使用Github和Docusaurus搭建wiki

2025 年 10 月 02 日 • 建站

这里使用Docusaurus作为wiki系统,可以基于markdown文件和文件夹自动生成文档。
另外将原始markdown文件托管在Github上,这样可以实现版本管理。当有变更推送到Github上时,Github通知wiki所在的服务器更新文档、重新构建wiki。

整体流程如下
l1UJiF

wiki服务器配置

需要在wiki服务器上启动Github webhook的监听。

这里通过systemd拉起监听脚本实现。

service文件:

[Unit]
Description=Docusaurus Auto Update Service
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/my-docusaurus
ExecStart=/usr/bin/node /var/www/my-docusaurus/auto-update.js
Restart=always

[Install]
WantedBy=multi-user.target

auto-update.js脚本:

const http = require('http');
const spawn = require('child_process').spawn;
const createHandler = require('github-webhook-handler');

const handler = createHandler({
  path: '/webhook',
  secret: 'your-webhook-secret'
});

http.createServer((req, res) => {
  handler(req, res, err => {
    res.statusCode = 404;
    res.end('no such location');
  });
}).listen(7777);

handler.on('error', err => {
  console.error('Error:', err.message);
});

handler.on('push', event => {
  console.log('Received push event');
  
  // 拉取最新代码
  const pull = spawn('git', ['pull']);
  
  pull.stdout.on('data', data => {
    console.log(`stdout: ${data}`);
  });
  
  pull.stderr.on('data', data => {
    console.error(`stderr: ${data}`);
  });
  
  pull.on('close', code => {
    if (code === 0) {
      console.log('Git pull successful');
      // 重新安装依赖(如果有变更)
      const install = spawn('npm', ['install']);
      
      install.on('close', code => {
        if (code === 0) {
          // 重新构建网站
          const build = spawn('npm', ['run', 'build']);
          build.on('close', code => {
            console.log(`Build process exited with code ${code}`);
          });
        }
      });
    }
  });
});

当然上面的脚本需要在服务器上安装github-webhook-handler:

sudo apt update
sudo apt install -y nodejs npm
npm install -g github-webhook-handler

另外需要实现在服务器上自启动:

sudo systemctl daemon-reload
sudo systemctl enable docusaurus-update.service
sudo systemctl start docusaurus-update.service

Github配置

Github上需要配置当接受到代码push的时候,通过webhook通知wiki服务器更新代码。

进入你的 GitHub 仓库 → Settings → Webhooks → Add webhook

Payload URL: http://your-server-ip:7777/webhook
Content type: application/json
Secret: your-webhook-secret(与脚本中一致)
选择事件:Just the push event

搞定后,就可以实现当有变更推送到Github上时,wiki服务器会接受到通知,这个时候主动拉取代码。