gitbook小记

GitBook: Document Everything!

GitBook是一个基于Node.js的命令行工具,可以输出 HTML、PDF、eBook 等格式的电子书。

本文记录了如何开始gitbook,以及github存储,通过git-auto-deploy工具部署服务器。

如何使用

gitbook是npm仓库里的一个包,提供了NPM方式的安装:

1
npm install gitbook-cli -g

创建mybook文件夹并初始化

1
mkdir mybook && cd mybook && gitbook init

可以看到有两个文件README.md和SUMMARY.md

生成电子书服务

1
gitbook serve

可以在终端看到,默认服务是localhost:4000,打开可以看到电子书了。

更新您的电子书,打开SUMMARY.md文件,修改为如下内容:

1
2
3
4
5
6
7
8
9
# Summary

This is the summary of my book.

* [section 1](section1/README.md)
* [example 1](section1/example1.md)
* [example 2](section1/example2.md)
* [section 2](section2/README.md)
* [example 1](section2/example1.md)

保存文件并执行gitbook init命令,它会帮我们生成对应的目录。再次执行gitbook serve命令,访问localhost:4000
gitbook init
gitbook serve

可以看到,gitbook帮我们生成了新的文件目录和文件,是不是很神奇!

有时候我们需要部署到服务器上,生成静态文件:

1
gitbook build

默认情况下,会在当前目录下生成_book文件夹,也可以通过指定输入输出的形式,输出到指定的文件夹。

1
2
## 注意:--output=后有空格
gitbook build ./ --output= /var/www/mybook

放到github仓库

在github上新创建一个项目,假如说是mybook项目,可以通过github pages来配置,这样就把项目部署到github pages里了

部署到服务器

首先安装Git-Auto-Deploy,参考Git-Auto-Deploy

1
2
3
4
git clone https://github.com/olipo186/Git-Auto-Deploy.git
cd Git-Auto-Deploy
pip install -r requirements.txt
cp config.json.sample config.json

编辑config.json

1
2
3
4
5
6
7
8
9
"repositories": [
{
"url": "https://github.com/dillonliang224/mybook.git", // github地址
"branch": "master",
"remote": "origin",
"path": "~/repositories/mybook", // 仓库地址
"deploy": "gitbook build ./ --output= /var/www/mybook" // 拉取mybook仓库后执行的命令
}
]

然后执行如下命令启动git-auto-deploy服务,默认是8001端口

1
python -m gitautodeploy --config config.json --allow-root-user

然后配置nginx,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server {
listen 80;
server_name study.dillonliang.cn;
root /usr/share/nginx/html;

location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://localhost:8001/;
}

error_page 404 /404.html;
location = /40x.html {
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}

也就是说,当我访问study.dillonliang.cn的时候,会转发至内部的8001端口。
重启nginx

配置github

参考 https://github.com/olipo186/Git-Auto-Deploy#getting-webhooks-from-git 配置代码仓库即可
github webhook

然后当写完我们的mybook文件后,提交文件到github,github会发送一个request到服务器,服务器拉取仓库代码并build mybook,等待一会,就可以看到我们的mybook在浏览器上可以访问了。我的mybook是: http://book.dillonliang.cn

后台运行git-auto-deploy服务

1
python -m gitautodeploy --config config.json --allow-root-user --daemon-mode

这样我的mybook可以自动发布到服务器上了。

总结

通过gitbook,了解了github webhook,也学会了用git-auto-deploy工具,这个工具也可以帮我部署测试代码,省了大量时间哈。

后续再写一个脚本发布本地的mybook到github就可以了。

至于gitbook编辑器和插件等,是对gitbook的锦上添花,可以自由选择。