-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
50 lines (46 loc) · 1.3 KB
/
server.js
File metadata and controls
50 lines (46 loc) · 1.3 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
const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = 3000;
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, req.url);
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(404, { "Content-Type": "text/json" });
res.end(
JSON.stringify(
{
error: true,
message: "File not found!",
},
null,
4
)
);
} else {
res.writeHead(200, { "Content-Type": getContentType(filePath) });
res.end(content);
}
});
});
server.listen(PORT, () => {
console.log(`Visit local website at http://localhost:${PORT}/index.html`);
});
function getContentType(filePath) {
const extname = path.extname(filePath);
switch (extname) {
case ".html":
return "text/html";
case ".css":
return "text/css";
case ".js":
return "text/javascript";
case ".png":
return "image/png";
case ".jpg":
case ".jpeg":
return "image/jpeg";
default:
return "application/octet-stream";
}
}