-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain-node.js
More file actions
102 lines (81 loc) · 2.29 KB
/
main-node.js
File metadata and controls
102 lines (81 loc) · 2.29 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
89
90
91
92
93
94
95
96
97
98
99
100
import http from "node:http";
import { readFile, lstat } from 'node:fs/promises';
import { join as joinPath, resolve as resolvePath } from 'node:path';
const MimeType = Object.freeze({
TEXT_HTML: "text/html",
TEXT_CSS: "text/css",
TEXT_XML: "text/xml",
IMAGE_GIF: "image/gif",
IMAGE_JPEG: "image/jpeg",
APPLICATION_JAVASCRIPT: "application/javascript",
IMAGE_PNG: "image/png",
IMAGE_TIFF: "image/tiff",
IMAGE_VND_WAP_WBMP: "image/vnd.wap.wbmp",
IMAGE_X_ICON: "image/x-icon",
IMAGE_X_JNG: "image/x-jng",
IMAGE_X_MS_BMP: "image/x-ms-bmp",
IMAGE_SVG_XML: "image/svg+xml",
IMAGE_WEBP: "image/webp",
});
const ExtMimeMapping = Object.freeze({
"html": MimeType.TEXT_HTML,
"htm": MimeType.TEXT_HTML,
"shtml": MimeType.TEXT_HTML,
"css": MimeType.TEXT_CSS,
"xml": MimeType.TEXT_XML,
"gif": MimeType.IMAGE_GIF,
"jpeg": MimeType.IMAGE_JPEG,
"jpg": MimeType.IMAGE_JPEG,
"js": MimeType.APPLICATION_JAVASCRIPT,
"png": MimeType.IMAGE_PNG,
"tif": MimeType.IMAGE_TIFF,
"tiff": MimeType.IMAGE_TIFF,
"wbmp": MimeType.IMAGE_VND_WAP_WBMP,
"ico": MimeType.IMAGE_X_ICON,
"jng": MimeType.IMAGE_X_JNG,
"bmp": MimeType.IMAGE_X_MS_BMP,
"svg": MimeType.IMAGE_SVG_XML,
"webp": MimeType.IMAGE_WEBP,
});
const baseDirectory= resolvePath(".");
const server = http.createServer(async(req, res) => {
if (req.url == null) {
res.statusCode = 400;
res.end("Bad Request");
return;
}
const urlPath = joinPath(baseDirectory, req.url);
try {
const fileStat= (await lstat(urlPath));
if (fileStat.isDirectory()) {
try {
const fileContent = await readFile(joinPath(urlPath, "index.html"), "utf-8")
res.writeHead(200, { "Content-Type": MimeType.TEXT_HTML });
res.end(fileContent, "utf-8")
} catch (e) {
res.statusCode = 404;
res.end("Not Found");
}
return;
} else {
res.writeHead(200, { "Content-Type": extToMime(req.url) });
res.end(await readFile(`.${req.url}`, "utf-8"), "utf-8")
return
}
} catch (e) {
res.statusCode = 404;
res.end("Not Found");
return;
}
});
server.listen(3000, () => {
console.log("Server running at http://127.0.0.1:3000/");
})
/**
*
* @param {string} url
*/
function extToMime(url) {
// @ts-ignore
return ExtMimeMapping[url.split('.').pop().toLowerCase()] ?? "text/plain";
}