-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
109 lines (99 loc) · 2.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* =================================
* @2018 塞伯坦CYBMOCK前端数据模拟服务器
* https://github.com/jd-cyb/cybmock
* =================================
*/
const nodemon = require('nodemon')
const path = require('path')
const fs = require('fs')
const browserSync = require('browser-sync').create();
const fsExtra = require('fs-extra')
const del = require('del')
const serverConfig = require('./lib/server.config')
module.exports = () => {
const cacheFile = path.join(process.cwd(), './.cache')
const mockRouterFile = path.join(process.cwd(), 'cybmock.config.js')
del.sync(cacheFile) //删除缓存文件
const checkCacheFile = () => {
let num = 0
return new Promise((resolve, reject) => {
const findCacheFile = () => {
if (!fs.existsSync(cacheFile)) {
setTimeout(() => {
findCacheFile()
num++
if (num >= 150) reject()
}, 100)
} else {
resolve()
}
}
findCacheFile()
})
}
if (!fs.existsSync(mockRouterFile)) {
const mockRouterTemp = `module.exports = {
'GET /api/demoGet': {
tips: '用于演示GET请求',
name: '塞伯坦前端模块化工程构建工具',
github: 'https://github.com/jd-cyb/cyb-cli'
},
'POST /api/demoPost': {
tips: '用于演示POST请求',
name: '塞伯坦前端数据模拟服务器',
github: 'https://github.com/jd-cyb/cybmock'
}
}
`
fs.writeFileSync(mockRouterFile, mockRouterTemp, 'utf8');
}
let started = false;
const stream = nodemon({
script: path.join(__dirname, './server.js'),
ext: "js",
env: {
'NODE_ENV': process.env.NODE_ENV
},
// 监听的路径
watch: [
path.join(process.cwd(), './mock'),
mockRouterFile
]
})
stream
.on('start', () => {
if (!started) {
checkCacheFile().then(() => {
fsExtra.readJson(cacheFile, (err, packageObj) => {
if (err) return console.error(err)
browserSync.init({
...serverConfig.browserSync,
proxy: `localhost:${packageObj.port}`
})
})
})
started = true;
}
})
.on('restart', () => {
setTimeout(() => {
checkCacheFile().then(() => {
browserSync.reload()
})
}, 100)
})
.on('crash', () => {
stream.emit('restart', 10)
})
.on('exit', () => {
del.sync(cacheFile) //删除缓存文件
if (stream.quitEmitted) {
process.exit(0)
}
})
process.on('SIGINT', () => {
stream.emit('quit')
stream.quitEmitted = true
})
}