-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
76 lines (65 loc) · 1.9 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
const chokidar = require('chokidar')
const { Server } = require('ws')
const StaticServer = require('./lib/server')
const defaultSubscribe = require('./lib/subscribe')
const defaultParams = require('./lib/params')
module.exports = class extends StaticServer {
constructor(watches = process.cwd(), publics) {
super(publics)
this.watches = watches
this.initialize()
}
initialize() {
this.timer = null
this.server = null
this.ws = null
this.watcher = null
this.clients = []
this.$subscribe = defaultSubscribe
}
set subscribe($subscribe) {
if (typeof $subscribe === 'function') {
this.$subscribe = $subscribe
}
}
close() {
this.watcher.close()
this.ws.close()
this.server.close()
this.initialize()
}
removeClient(client) {
this.clients = this.clients.filter(c => c !== client)
this.$subscribe({ ...defaultParams, clients: this.clients.length })
}
start(port = 2333) {
if (this.server) {
this.$subscribe({ ...defaultParams, status: 'running' })
return
}
this.server = this.create(port)
this.watcher = chokidar.watch(this.watches, {
ignored: /(^|[/\\])\../,
ignoreInitial: true,
})
this.watcher.on('all', (event, filePath) => {
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.$subscribe({
...defaultParams,
event,
path: filePath,
trigger: type => this.clients.forEach(client => client.send(type)),
})
}, 100)
})
this.ws = new Server({ server: this.server })
this.ws.on('connection', (client) => {
client.on('close', () => this.removeClient(client))
client.on('error', () => this.removeClient(client))
this.clients.push(client)
this.$subscribe({ ...defaultParams, clients: this.clients.length })
})
this.$subscribe({ ...defaultParams, port, status: 'start' })
}
}