-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
63 lines (53 loc) · 1.27 KB
/
app.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
/*eslint no-console: ["error", { allow: ["log","warn", "error"] }] */
const path = require('path');
const state = {
server: null,
sockets: []
};
function start(){
state.server = require('./server')().listen(3000,() => {
console.log('Started on 3000');
});
state.server.on('connection',(socket) => {
console.log('Add socket',state.sockets.length + 1);
state.sockets.push(socket);
});
}
function pathCheck(id){
return (
id.startsWith(path.join(__dirname,'routes')) ||
id.startsWith(path.join(__dirname,'server.js'))
);
}
function restart(){
//clean the cache
Object.keys(require.cache).forEach((id) => {
if (pathCheck(id)){
console.log('Reloading',id);
delete require.cache[id];
}
});
state.sockets.forEach((socket,index) => {
console.log('Destroying socket',index + 1);
if (socket.destroyed === false){
socket.destroy();
}
});
state.sockets = [];
state.server.close(() => {
console.log('Server is closed');
console.log('\n----------------- restarting -------------');
start();
});
}
start();
const chokidar = require('chokidar');
chokidar.watch(['./routes','./server.js']).on('all',(event,at) => {
if (event === 'add'){
console.log('Watching for',at);
}
if (event === 'change'){
console.log('Changes at',at);
restart();
}
});