-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
72 lines (62 loc) · 1.47 KB
/
server.ts
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
import fastify from 'fastify';
import { PassThrough } from 'stream';
const defaults = {
dir: process.cwd(),
port: 3000,
livePort: 35729,
address: '0.0.0.0',
quiet: false,
};
export default async (options) => {
const {
dir,
port,
livePort,
address,
quiet,
}: any = {
...defaults,
...options,
};
const server = fastify({
logger: !quiet,
});
server.register(require('fastify-static'), {
root: dir,
});
server.addHook('onSend', async (request, reply, payload: any) => {
if (
(payload as any).filename
&& (/.html$/).test((payload as any).filename)
) {
let newPayload = '';
await (
new Promise(
resolve => (
payload as PassThrough
)
.on('data', (chunk) => newPayload += chunk)
.on('finish', resolve)
)
);
newPayload = newPayload.replace(
'</body>',
`<script>
document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] +
':${livePort}/livereload.js?snipver=1"></' + 'script>')
</script></body>`
);
reply.header('content-length', Buffer.from(newPayload).length);
return newPayload;
}
return payload;
});
try {
await server.listen(port, address, () => {
console.log(`🔥 Fast Hot Reload is running on http://${address}:${port}`);
});
} catch (err) {
server.log.error(err);
process.exit(1);
}
};