-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
52 lines (46 loc) · 1.48 KB
/
app.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
import http from "http";
import { readFile } from "fs/promises";
import { extname, resolve } from "path";
import mimeTypes from "./constants/mimeTypes.js";
import SERVER_CONFIG from "./constants/serverConfig.js";
const server = http.createServer(async (req, res) => {
const publicDir = resolve("public");
let filePath = req.url === "/" ? "index.html" : req.url.slice(1);
filePath = resolve(publicDir, filePath);
const ext = extname(filePath);
const contentType = mimeTypes[ext] || "application/octet-stream";
try {
const content = await readFile(filePath, {
encoding: contentType.startsWith("text/") ? "utf-8" : null,
});
res.writeHead(200, { "Content-Type": contentType });
res.end(content);
} catch (error) {
if (error.code === "ENOENT") {
try {
const errorPageContent = await readFile(
resolve(publicDir, "404.html"),
"utf-8"
);
res.writeHead(404, { "Content-Type": "text/html" });
res.end(errorPageContent);
} catch (error404) {
res.writeHead(500);
res.end(
`Sorry, check with the site admin for error: ${error404.code} ..\n`
);
}
} else {
res.writeHead(500);
res.end(`Sorry, check with the site admin for error: ${error.code} ..\n`);
}
}
});
const { HOST, PORT } = SERVER_CONFIG;
server.listen(PORT, HOST, (err) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server running on http://${HOST}:${PORT}`);
});