-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
83 lines (66 loc) · 2.38 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
77
78
79
80
81
82
83
const http2 = require("http2");
const fs = require("fs");
const path = require("path");
const util = require("util");
const open = util.promisify(fs.open);
const stat = util.promisify(fs.stat);
const exists = util.promisify(fs.exists);
const readFile = util.promisify(fs.readFile);
const { findPushFiles, getFilePath } = require("./discover");
const extTypeMap = {
".html": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".wasm": "application/wasm"
};
const acceptedRequests = {
"/": "/index.html",
"/index.html": "/index.html",
"/logic/store.js": "/logic/store.js",
"/sw.js": "/sw.js",
"/rust/debug/2048.wasm": "/rust/debug/2048.wasm",
"/rust/release/2048.wasm": "/rust/release/2048.wasm"
};
const server = http2.createSecureServer({
key: fs.readFileSync("certs/localhost-privkey.pem"),
cert: fs.readFileSync("certs/localhost-cert.pem")
});
server.on("error", err => console.error("error", err));
server.on("socketError", err => console.error(err));
const send = async (stream, requestPath, log = "send") => {
const filePath = path.join(__dirname, "public", requestPath);
const fd = await open(filePath, "r");
const ext = path.extname(filePath);
const statData = await stat(filePath);
const headers = {
"content-length": statData.size,
"last-modified": statData.mtime.toUTCString(),
"content-type": `${extTypeMap[ext]}`
};
console.log(log, requestPath);
stream.respondWithFD(fd, headers);
};
const push = (stream, filePath, from = null) => {
stream.pushStream({ ":path": filePath }, (err, pushStream) => {
pushStream.on("error", error => console.error("Push stream error", error));
send(pushStream, filePath, `push from ${from}`);
});
};
server.on("stream", async (stream, headers) => {
console.log("request", headers[":path"]);
stream.on("error", error => console.error("Stream error", error));
if (Object.keys(acceptedRequests).includes(headers[":path"])) {
const request = acceptedRequests[headers[":path"]];
let pushFiles = await findPushFiles(request);
pushFiles = Array.from(new Set(pushFiles));
pushFiles.forEach(pushFile => {
push(stream, pushFile, request);
});
send(stream, request);
} else {
stream.respond({ ":status": 404 });
stream.end();
}
});
server.on("error", error => console.error("Server error", error));
server.listen(8443);