-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
42 lines (37 loc) · 1 KB
/
server.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
const http = require("http");
const fs = require("fs");
const path = require("path");
function serveInternalServerErr(resp) {
resp.writeHead(500);
resp.end("500: Internal Server Error");
}
const server = http.createServer((req, resp) => {
let fpath = `.${req.url}`;
if (fpath === "./") {
fpath = "./index.html";
}
const mimeTypes = {
".html": "text/html",
".js": "text/javascript",
".css": "text/css",
};
const contentType = mimeTypes[path.extname(fpath)];
fs.readFile(fpath, (error, content) => {
if (!error) {
resp.writeHead(200, { "Content-Type": contentType });
resp.end(content, "utf-8");
} else if (error.code === "ENOENT") {
fs.readFile("./404.html", (error, content) => {
if (error) {
serveInternalServerErr(resp);
return;
}
resp.writeHead(404, { "Content-Type": "text/html" });
resp.end(content, "utf-8");
});
} else {
serveInternalServerErr(resp);
}
});
});
server.listen(8000);