forked from getsentry/sentry-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhotReloadWatcher.mjs
53 lines (46 loc) · 1.29 KB
/
hotReloadWatcher.mjs
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
import path from 'path';
import {watch} from 'node:fs/promises';
import {WebSocketServer} from 'ws';
const watchedContent = new Set(['.mdx', '.md', '.png', '.jpg', '.jpeg', '.gif', '.svg']);
export const throttle = (fn, delay) => {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last < delay) {
return;
}
last = now;
return fn(...args);
};
};
const wss = new WebSocketServer({port: 8080});
console.info('⚡️ Hot reload watcher listening on ws://localhost:8080');
wss.on('connection', async function onConnect(ws) {
ws.on('error', err => {
console.log('ws error', err);
});
ws.on('message', function incoming(_msg) {
// no reason for the client to send messages for now
});
const ac = new AbortController();
const {signal} = ac;
ws.on('close', () => ac.abort());
// avoid fileystem chatter when you save a file
const sendReload = throttle(() => ws.send('reload'), 10);
try {
const watcher = watch(path.join(import.meta.dirname, '..', 'docs'), {
signal,
recursive: true,
});
for await (const event of watcher) {
if (watchedContent.has(path.extname(event.filename))) {
sendReload();
}
}
} catch (err) {
if (err.name === 'AbortError') {
return;
}
throw err;
}
});