-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEntry.js
98 lines (86 loc) · 2.4 KB
/
Entry.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//@ts-check
const express = require("express");
const FileSystem = require("fs");
const path = require("path");
const app = express();
const port = 80;
app.get(
"/chat",
ServeFile(path.join(__dirname, "./chatTools/assets/chat.html"))
);
app.get(
"/favicon.ico",
ServeFile(path.join(__dirname, "./assets/images/favicon.ico"))
);
app.use(
"/chat/assets/",
express.static(path.join(__dirname, "./chatTools/assets"))
);
app.listen(port, () => {
console.log(`Server listening on port: ${port}`);
});
/**
* @param {String} AbsolutePath
* @param {String | null} contentType
*/
function ServeFile(AbsolutePath, contentType = null) {
if (!path.isAbsolute(AbsolutePath)) {
throw new Error(
`filePath isn't absolute, requests won't work correctly: ${AbsolutePath}`
);
}
let fileExt = path.extname(AbsolutePath);
/**
* @type {String | null}
*/
let Type = contentType;
if (!Type) {
switch (fileExt) {
case ".js":
Type = "text/javascript";
break;
case ".css":
Type = "text/css";
break;
case ".html":
Type = "text/html";
break;
case ".json":
Type = "application/json";
break;
case ".png":
Type = "image/png";
break;
case ".jpg":
Type = "image/jpg";
break;
case ".ico":
Type = "image/x-icon";
break;
case ".svg":
Type = "image/svg+xml";
break;
default:
console.log(`couldn't infer filetype assuming plaintext...`);
Type = "text/plain";
break;
}
}
return (req, res) => {
FileSystem.readFile(AbsolutePath, (err, data) => {
if (err) {
console.log(AbsolutePath);
console.log(err.message);
res.statusCode = 500;
res.setHeader("Content-Type", "text/plain");
res.end("Server Error");
return;
}
console.log(`Serving ${AbsolutePath}, as ${Type}...`);
res.statusCode = 200;
res.setHeader("Content-Type", Type);
res.end(data);
return;
});
};
}