-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
116 lines (103 loc) · 2.57 KB
/
server.js
File metadata and controls
116 lines (103 loc) · 2.57 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
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
105
106
107
108
109
110
111
112
113
114
115
116
// bem130
const http = require("http");
const fs = require('fs');
const url = require('url');
const port1 = 8000;
http.createServer(server_request).listen(port1);
let mime = {
"txt":"text/plain; charset=UTF-8",
"html":"text/html; charset=UTF-8",
"css":"text/css; charset=UTF-8",
"nml":"text/neknajml; charset=UTF-8",
"js":"text/javascript",
"png":"image/png",
"jpg":"image/jpeg",
"jpeg":"image/jpeg",
"gif":"image/gif",
};
function server_request(req, response) {
let head = {code:200,type:"text/plain; charset=UTF-8",filetype:"txt"};
let res = "";
//
// transfer
//
let reqparse = url.parse(req.url);
let requrl = req.url;
switch (reqparse.pathname) {
case "/404":
case "/404.html":
head.code = 404;
break;
case "/": // top page
reqparse.pathname = "/index.html";
break;
}
//
// end
//
//
// get file
//
let filepath = "data"+reqparse.pathname;
if (reqparse.pathname.endsWith(".ntkd")) {
filepath = "keyboards"+reqparse.pathname;
}
if (fs.existsSync(filepath)) {
res = fs.readFileSync(filepath);
}
else if (fs.existsSync(filepath+".html")) {
res = fs.readFileSync(filepath+".html");
reqparse.pathname += ".html";
}
else {
res = fs.readFileSync("data/404.html");
reqparse.pathname += ".html";
head.code = 404;
}
//
// end
//
//
// set MIME
//
let fnsplit = reqparse.pathname.split(".");
head.filetype = fnsplit[fnsplit.length-1];
if (mime[head.filetype]!=null) {
head.type = mime[head.filetype];
}
//
// end
//
//
// replace dynamic infos
//
if (head.filetype=="html") {
res = (new TextDecoder("utf-8")).decode(new Uint8Array(res));
res = res.replace(/\[\*accesstime\]/g,(new Date()).toLocaleString());
}
//
// end
//
//
// response
//
// Access
response.setHeader('Access-Control-Allow-Origin', '*');
// data
response.writeHead(head.code, {"Content-Type": head.type});
response.end(res);
//
// end
//
//
// push log
//
// console.log(req.rawHeaders[3])
let log = `\x1b[33m${(new Date()).toLocaleString()}\x1b[39m requrl: \x1b[34m${req.url}\x1b[39m path: \x1b[34m${reqparse.path}\x1b[39m response: \x1b[36m${head.code}\x1b[39m res: \x1b[35m${reqparse.pathname}\x1b[39m\nUA: \x1b[34m${req.rawHeaders} \x1b[39m\n`
console.log(log);
//fs.appendFile("./serverlog.log", log,()=>{});
//
// end
//
}
console.log(`The server has started: ${port1}`);