-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
104 lines (92 loc) · 2.59 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const http = require("http"),
fs = require("fs"),
ejs = require("ejs"),
parseLang = require("accept-language-parser");
function pageRoute(req, res) {
let reqContentType = "HTML";
let prefix = "/files/";
res.setHeader("Content-Type", "text/html");
path = "./dynamic/";
res.statusCode = 200;
switch (req.url) {
case "/":
text = "Home";
path += "index.ejs";
ejs_values = { css: `${prefix}home.css` };
break;
case "/create-form":
text = "Create Form";
path += "create-form.ejs";
ejs_values = {
css: `${prefix}create-form.css`,
js: [
`${prefix}utility.js`,
`${prefix}ui-functions.js`
]
};
break;
case "/forms":
text = "Forms";
break;
default:
text = "404";
path += "404.ejs";
ejs_values = { css: `${prefix}404.css` };
res.statusCode = 404;
break;
}
return { path, text, reqContentType, ejs_values };
}
function fileRoute(req, res) {
var reqContentType;
let prefix = "/files/";
//let css = "./css/";
//let images = "./images/";
let ext = req.url.split(".").pop();
let filename = req.url.split("/").pop();
path = ""; // reset or empty path
if (ext === "css") { path = "./css/"; reqContentType = "Stylesheet" }
else if ( ext === "webp" | ext === "svg" ) { path = "./images/"; reqContentType = "Image" }
else if (ext === "js") { path = "./js_modules/"; reqContentType = "Javascript" }
text = filename;
path += filename;
return { path, text, reqContentType };
}
http.createServer((req, res) => {
var route;
let fileRegex = /^\/files\//;
let isFile = fileRegex.test(req.url);
if (isFile) {
route = fileRoute(req, res);
if (fs.existsSync(route.path)) { res.statusCode = 200 }
else { res.statusCode = 404 }
console.log("\x1b[32m","\nFile", "\x1b[0m");
} else {
route = pageRoute(req, res);
console.log("\n" + "\x1b[43m\x1b[30m%s\x1b[0m", " Page --------- ");
}
let text = route.text;
let path = route.path;
let ejs_values = route.ejs_values;
console.log("URL: " + req.url);
console.log("Path: " + path);
console.log(req.method + " " + res.statusCode + " " + text);
fs.readFile(path, (err, data) => {
if (err) {
console.log(err);
res.write("No Content");
res.statusCode = 404;
res.end();
} else {
if (route.reqContentType === "HTML") {
Object.assign(ejs_values, {filename: path});
res.end(ejs.render(data.toString(), ejs_values));
} else if (route.reqContentType === "Javascript") { // fixes browser MIME type error
res.setHeader("Content-Type", "text/javascript");
res.end(data);
} else { res.end(data) }
}
});
}).listen(3000, () => {
console.log("Listening on port 3000");
});