-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.js
45 lines (40 loc) · 1.17 KB
/
init.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
const serve_handler = require('serve-handler')
const { createServer: create_server } = require('http')
const {
Server: websocket_server_instance,
OPEN: websocket_open_state,
} = require('ws')
const chokidar = require('chokidar')
const { resolve, relative } = require('path')
const in_production = process.env.NODE_ENV === 'production'
const http_server = create_server({}, (request, response) => {
return serve_handler(request, response, {
public: './',
etag: true,
rewrites: [
{
source: '/',
destination: in_production ? '/index.html' : '/index.dev.html',
},
],
})
})
const websocket_server = new websocket_server_instance({
server: http_server,
})
http_server.listen(80, () => {
console.log('Running at http://localhost:80')
})
chokidar.watch(resolve('./')).on('change', (path) => {
websocket_server.clients.forEach((client) => {
if (client.readyState === websocket_open_state) {
client.send(
JSON.stringify({
// transform relative fs path to path from root of server path
path: `/${relative(resolve('./'), path).replace(/\\/g, '/')}`,
event: 'changed',
}),
)
}
})
})