本教程 總體開發環境爲 nodejs nodejs.org/en/node
本教程 涉及到的2個項目的部署採用 pm2 pm2.keymetrics.io/webpack
本教程 涉及到的2個項目的端口代理採用 nginx nginx newsnginx
本教程 涉及到的2個項目的 git代碼託管爲 碼雲 碼雲 - 開源中國git
本教程 涉及到的mock項目的自動化部署基於的碼雲平臺的webhook回調, 使用說明在這裏 碼雲平臺幫助文檔_V1.2github
本教程 含有2個項目, 包括:web
1. mock服務器 涉及到的知識有:shell
2. mock服務自動化部署腳本 涉及到的知識有:express
本教程 涉及的項目中 依賴庫的安裝均使用淘寶鏡像代替npmnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org複製代碼
一. mock服務器項目的實現json
mock服務器項目總體目錄
具體流程爲:
1. 初始化一個nodejs項目
npm init複製代碼
2. 項目的package.json文件以下, 在根目錄執行 cnpm install 安裝全部依賴庫
{
"name": "mock-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"mock": "gulp mock"
},
"repository": {
"type": "git",
"url": "git@git.oschina.net:xxx/xxx.git"
},
"author": "",
"license": "ISC",
"devDependencies": {
"json-server": "^0.11.2",
"mockjs": "^1.0.1-beta3",
"browser-sync": "^2.18.12",
"gulp": "^3.9.1",
"gulp-nodemon": "^2.2.1"
}
}
複製代碼
3. 在 /mock/ 目錄下 建立如下3個文件
db.js 數據源文件
routes.js 接口路由
server.js json-server服務
# db.js
var Mock = require('mockjs')
var Random = Mock.Random
module.exports = {
userInfo: Mock.mock({
'code': 1,
'data': {
'uid': '582028',
'username': 'sufaith',
'phone': '12345678910'
}
})
}
複製代碼
# routes.js
module.exports = {
'/getUserInfo': '/userInfo'
}
# server.js
const jsonServer = require('json-server')
const db = require('./db.js')
const routes = require('./routes.js')
const port = 3000
const server = jsonServer.create()
const router = jsonServer.router(db)
const middlewares = jsonServer.defaults()
const rewriter = jsonServer.rewriter(routes)
server.use(middlewares)
// 將 POST 請求轉爲 GET
server.use((request, res, next) => {
request.method = 'GET'
next()
})
server.use(rewriter) // 注意:rewriter 的設置必定要在 router 設置以前
server.use(router)
server.listen(port, () => {
console.log('open mock server at localhost:' + port)
})
複製代碼
4.本地修改數據時爲了實時查看效果, 使用gulp監聽文件數據的更新,自動重啓json-server
# gulpfile.js
const path = require('path')
const gulp = require('gulp')
const nodemon = require('gulp-nodemon')
const browserSync = require('browser-sync').create()
const server = path.resolve(__dirname, 'mock')
// browser-sync 配置,配置裏啓動 nodemon 任務
gulp.task('browser-sync', ['nodemon'], function () {
browserSync.init(null, {
proxy: 'http://localhost:3000', // web端本地測試用,這裏的端口和 webpack 的端口一致
port: 3001
})
})
// browser-sync 監聽文件
gulp.task('mock', ['browser-sync'], function () {
gulp.watch(['./mock/db.js', './mock/**'], ['bs-delay'])
})
// 延時刷新
gulp.task('bs-delay', function () {
setTimeout(function () {
browserSync.reload()
}, 1000)
})
// 服務器重啓
gulp.task('nodemon', function (cb) {
// 設個變量來防止重複重啓
var started = false
var stream = nodemon({
script: './mock/server.js',
// 監聽文件的後綴
ext: 'js',
env: {
'NODE_ENV': 'development'
},
// 監聽的路徑
watch: [
server
]
})
stream.on('start', function () {
if (!started) {
cb()
started = true
}
}).on('crash', function () {
console.error('application has crashed!\n')
stream.emit('restart', 10)
})
})
複製代碼
5. 建立pm2所需的 配置文件 process.json
#process.json
{
"apps": [
{
"script": "mock/server.js",
"error_file" : "pm2_log/error.log",
"out_file" : "pm2_log/out.log",
"merge_logs" : true,
"log_date_format" : "YYYY-MM-DD HH:mm Z"
}
]
}
複製代碼
6. 上傳至線上服務器, 進入項目根目錄, 執行pm2運行命令
pm2 start process.json複製代碼
而後在控制檯執行 pm2 list 命令, 若是出現如下,則證實已開啓後臺運行
7. 使用nginx開啓反向代理, 使用域名訪問 (不須要的能夠跳過該步奏)
二. mock服務自動化部署腳本的實現
具體流程爲:
1. 新建nodejs項目, 用於接收 webhook回調
node init複製代碼
2. 項目的package.json文件以下, 在根目錄執行 cnpm install 安裝全部依賴庫
{
"name": "mock_webhook",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"body-parser": "^1.17.2",
"express": "^4.15.3"
}
}
複製代碼
3. 編寫app.js用於接收webhook回調地址, 以及自動執行shell命令
// app.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// 衍生一個 shell 並在 shell 上運行命令,當完成時會傳入 stdout 和 stderr 到回調函數
const exec = require('child_process').exec
// mock服務器項目地址
const projectPath = '/usr/local/www/mock-server'
// webhook 回調時攜帶的密碼,防止URL被惡意請求
const webhookPassword = 'test123456'
// 進入到mock服務器項目, 並執行 git pull的shell命令
const cmd_str_gitPull = `cd ${projectPath} && git pull origin master`
// 重啓mock服務器的shell命令
const cmd_str_restartJsonServer = `pm2 restart server`
const hostname = '127.0.0.1'
const port = 3001
app.post('/webhook', (req, res) => {
try {
let body = req.body
if(body.hook_name === 'push_hooks') {
if(body.password === webhookPassword) {
exec(cmd_str_gitPull, (error, stdout, stderr) => {
if(error) {
res.send(`exec gitPull error ${error}`)
}else {
exec(cmd_str_restartJsonServer, (error, stdout, stderr) => {
if (error) {
res.send(`exec restartJsonServer error ${error}`)
}else {
res.send('restartJsonServer success')
}
})
}
})
}else {
res.send('hook password error')
}
}else {
res.send('hook_name is not push_hooks')
}
}catch(err) {
res.send(`exception >>>${err}`)
}
})
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`)
})
複製代碼
4. 將該項目上傳至 和mock服務同一臺線上服務器中,進入項目目錄, 使用pm2部署
pm2 start app.js複製代碼
而後在控制檯執行 pm2 list 命令, 若是出現如下,則證實已開啓後臺運行
5. 使用nginx開啓反向代理, 使用域名訪問 (不須要的能夠跳過該步奏)
6. 在碼雲平臺中, 本身的mock服務器項目 的webhook管理中,配置自動化部署的post地址及密碼, 點擊測試查看是否響應