-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·85 lines (71 loc) · 1.93 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
#!/usr/bin/env node
const { spawn } = require("child_process");
const chokidar = require('chokidar');
const path = require("path");
let nodeProcess = null;
let processExited = true
let pathsToWatch = [
path.join(process.cwd()+'/models', "/**/*.js")
]
let previousReloadTimer = null;
init()
function init() {
nodeProcess = startProcess()
watchFiles()
process.on('SIGINT', async () => { await exitHandler() })
process.on('SIGTERM', async () => { await exitHandler() })
process.stdin.on('data', async (chunk) => {
const data = chunk.toString()
if (data.includes('rs')) {
await reload()
}
})
}
function startProcess() {
let childProcess = spawn('node', [__dirname+'/server.js'], {
stdio: [process.stdin, process.stdout, process.stderr]
})
processExited = false
childProcess.on('close', () => {
processExited = true
console.log('server restarting')
})
childProcess.on('error', () => {
processExited = true
console.log('Error occured')
})
return childProcess
}
function watchFiles() {
chokidar
.watch(pathsToWatch, {
ignored: "**/node_modules/*",
ignoreInitial: true
})
.on('all', async () => {
console.log("files modified...")
let debouncedTimer = setTimeout(async () => {
clearTimeout(previousReloadTimer)
await reload()
}, 1000)
previousReloadTimer = debouncedTimer
})
}
async function reload() {
await stopProcess();
nodeProcess = startProcess()
}
async function stopProcess() {
return new Promise((resolve, reject) => {
nodeProcess.kill()
const key = setInterval(() => {
if (processExited) { }
clearInterval(key)
resolve(true)
}, 500)
})
}
async function exitHandler() {
await stopProcess()
process.exit()
}