-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
83 lines (73 loc) · 2.24 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
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
const http = require('http');
const fs = require('fs');
const port = process.env.port || 1337;
console.log(`Server listening on http://localhost:${port}/`);
var redirectPage = '<!DOCTYPE html><html><head><meta charset="utf-8" /><meta http-equiv="refresh" content="0; url=./dist/" /><title></title></head><body></body></html>';
const MEDIA_TYPES = {
"md": "text/markdown",
"html": "text/html",
"htm": "text/html",
"txt": "text/plain",
"css": "text/css",
"ico": "image/ico",
"gif": "image/gif",
"jpg": "image/jpg",
"png": "image/png",
"json": "application/json",
"map": "application/json",
"js": "application/javascript",
"mjs": "application/javascript",
"woff": "font/woff",
"woff2": "font/woff2"
}
http.createServer(function (req, res) {
//console.log(req.url);
//when empty, redirect
if (req.url === "/") {
res.writeHead(200, { 'Content-Type': MEDIA_TYPES["html"] });
res.write(redirectPage);
return res.end();
}
let url = req.url;
let ext = "";
// Remove any params from query string
if (url.indexOf("?") > -1) {
url = url.substr(0, url.indexOf("?"));
}
// Fetch root default document, favicon, or any other files
if (req.url.endsWith("/")) {
url = `${req.url}index.html`;
ext = "html";
}
else if (req.url === "/favicon.ico") {
//Chrome browser asking for icon
url = `/dist${req.url}`;
ext = "ico";
}
else if (url.lastIndexOf(".") > -1) {
let s = url.split(".");
if (s.length > 0 ) {
ext = s[s.length - 1];
}
}
url = `.${url}`;
fs.exists(url, function (exist) {
if (!exist) {
console.log("404 (Not Found): " + url);
res.writeHead(404);
return res.end();
}
else {
fs.readFile(url, function(err, data) {
if (err !== null) {
res.writeHead(500);
res.write(err.message);
return res.end();
}
res.writeHead(200, { 'Content-Type': MEDIA_TYPES[ext] });
res.write(data);
return res.end();
});
}
});
}).listen(port);