-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
88 lines (73 loc) · 2.08 KB
/
Copy pathserver.mjs
File metadata and controls
88 lines (73 loc) · 2.08 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
import { createReadStream } from 'node:fs';
import http from 'node:http';
import { stat } from 'node:fs/promises';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { handler } from './build/handler.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const serviceWorkerPath = join(__dirname, 'build/client/service-worker.js');
const host = process.env.HOST ?? '0.0.0.0';
const port = Number(process.env.PORT ?? '3000');
const serviceWorkerHeaders = {
'cache-control': 'no-store, no-cache, max-age=0, must-revalidate',
'content-type': 'text/javascript; charset=utf-8',
'service-worker-allowed': '/',
};
const server = http.createServer(async (req, res) => {
if (isServiceWorkerRequest(req)) {
await serveServiceWorker(req, res);
return;
}
handler(req, res, (err) => {
if (err) {
console.error(err);
res.statusCode = 500;
res.end('Internal server error');
return;
}
res.statusCode = 404;
res.end('Not found');
});
});
server.listen(port, host, () => {
console.log(`Listening on http://${host}:${port}`);
});
process.on('SIGTERM', () => closeGracefully('SIGTERM'));
process.on('SIGINT', () => closeGracefully('SIGINT'));
function isServiceWorkerRequest(req) {
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
try {
return new URL(req.url ?? '/', 'http://localhost').pathname === '/service-worker.js';
} catch {
return false;
}
}
async function serveServiceWorker(req, res) {
try {
const file = await stat(serviceWorkerPath);
res.writeHead(200, {
...serviceWorkerHeaders,
'content-length': file.size,
'last-modified': file.mtime.toUTCString(),
});
if (req.method === 'HEAD') {
res.end();
return;
}
createReadStream(serviceWorkerPath).pipe(res);
} catch (error) {
console.error(error);
res.statusCode = 500;
res.end('Unable to load service worker');
}
}
function closeGracefully(signal) {
server.close((error) => {
if (error) {
console.error(error);
process.exit(1);
}
process.exit(signal === 'SIGTERM' ? 0 : 130);
});
}