-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.js
233 lines (208 loc) · 7.08 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
* a barebones HTTP server in JS
* originally by:
*
* @author zz85 https://github.com/zz85
*
* and modified by Croquet Corp
*
* Usage: node server.js <port number>
*
* do not use in production servers
*/
let port = 8000,
http = require('http'),
urlParser = require('url'),
fs = require('fs'),
path = require('path'),
currentDir = process.cwd();
port = process.argv[2] ? parseInt(process.argv[2], 0) : port;
function fileTypes(name) {
if (name.endsWith(".mjs")) {
return "application/javascript";
}
if (name.endsWith(".js")) {
return "application/javascript";
}
if (name.endsWith(".css")) {
return "text/css";
}
if (name.endsWith(".png")) {
return "image/png";
}
if (name.endsWith(".svg")) {
return "image/svg+xml";
}
if (name.endsWith(".html")) {
return "text/html";
}
if (name.endsWith(".pdf")) {
return "application/pdf";
}
if (name.endsWith(".wasm")) {
return "application/wasm";
}
return "application/octet-stream";
}
function header(type) {
let base = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, PUT, PROPFIND",
"Access-Control-Allow-Headers": "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range",
"Access-Control-Max-Age": "0",
"Cache-Control": "no-cache"
};
if (type) {
base["Content-Type"] = type;
}
return base;
}
function get(request, response, pathname) {
if (pathname.endsWith('/')) {pathname += 'index.html';}
let filePath = path.join(currentDir, pathname);
fs.stat(filePath, (err, stats) => {
if (err) {
response.writeHead(404, {});
response.end('File not found!');
return;
}
if (stats.isFile()) {
fs.readFile(filePath, (resErr, data) => {
if (resErr) {
response.writeHead(404, {});
response.end('Resource not found');
return;
}
let type = fileTypes(filePath);
response.writeHead(200, header(type));
response.write(data);
response.end();
});
} else if (stats.isDirectory()) {
fs.readdir(filePath, (error, files) => {
if (error) {
response.writeHead(500, {});
response.end();
return;
}
if (!pathname.endsWith('/')) {pathname += '/';}
response.writeHead(200, {'Content-Type': "text/html"});
response.write('<!DOCTYPE html>\n<html><head><meta charset="UTF-8"><title>' + filePath + '</title></head><body>');
response.write('<h1>' + filePath + '</h1>');
response.write('<ul style="list-style:none;font-family:courier new;">');
files.unshift('.', '..');
files.forEach((item) => {
let urlpath = pathname + item,
itemStats = fs.statSync(currentDir + urlpath);
if (itemStats.isDirectory()) {
urlpath += '/';
item += '/';
}
response.write(`<li><a href="${urlpath}">${item}</a></li>`);
});
response.end('</ul></body></html>');
});
}
});
}
function put(request, response, pathname) {
let filePath = path.join(currentDir, pathname);
let buf;
request.on('data', (chunk) => {
try {
if (!buf) {
buf = chunk;
} else {
buf = Buffer.concat([buf, chunk]);
}
} catch (e) {
console.log(e);
}
});
request.on('end', () => {
let dirname = path.dirname(filePath);
fs.mkdir(dirname, { recursive: true }, (err) => {
if (err) {
response.statusCode = 404;
response.setHeader('Content-Type', 'text/html');
response.end(`<h1>Cannot Create Directory</h1>\n<p>${dirname}</p>`);
return;
}
fs.writeFile(filePath, buf, (writeErr) => {
if (writeErr) {
response.statusCode = 404;
response.setHeader('Content-Type', 'text/html');
response.end(`<h1>Cannot Save File</h1>\n<p>${filePath}</p>`);
return;
}
console.log(filePath + ' saved (' + buf.length + ')');
response.statusCode = 200;
response.setHeader('Content-Type', 'text/plain');
response.end('');
});
});
});
}
function propfind(request, response, pathname) {
let dirname = path.dirname(pathname);
fs.stat(dirname, (err, stats) => {
if (err) {
console.log('error', err);
response.statusCode = 404;
response.setHeader('Content-Type', 'text/html');
response.end(`<h1>Directory Not found</h1>\n<p>${dirname}</p>`);
return;
}
if (!stats.isDirectory()) {
response.statusCode = 404;
response.setHeader('Content-Type', 'text/html');
response.end(`<h1>Directory Not found</h1>\n<p>${dirname}</p>`);
return;
}
fs.readdir(dirname, (readErr, list) => {
if (readErr) {
response.statusCode = 404;
response.setHeader('Content-Type', 'text/html');
response.end(`<h1>Cannot Read Directory</h1>\n<p>${dirname}</p>`);
return;
}
response.statusCode = 200;
response.setHeader('Content-Type', 'text/plain');
response.end(JSON.stringify(list));
});
});
}
function handleRequest(request, response) {
let urlObject = urlParser.parse(request.url, true);
let pathname = decodeURIComponent(urlObject.pathname);
let method = request.method;
if (method === "GET" && pathname.endsWith("/")) {
pathname += "index.html";
}
let filePath = path.join(currentDir, pathname);
let normalized = path.dirname(path.normalize(filePath));
if (normalized.slice(0, currentDir.length) !== currentDir) {
response.writeHead(403, {});
response.end();
return;
}
console.log(`[${(new Date()).toUTCString()}] "${method} ${pathname}"`);
if (method === 'GET') {
return get(request, response, pathname);
}
/*
if (method === 'PUT') {
return put(request, response, pathname);
}
if (method === 'PROPFIND') {
return propfind(request, response, pathname);
}
*/
return null;
}
http.createServer(handleRequest).listen(port);
require('dns').lookup(require('os').hostname(), (err, addr, _fam) => {
console.log(`Running at http://${addr === undefined ? "localhost" : addr}${((port === 80) ? '' : ':')}${port}/`);
});
console.log('The simple server has started...');
console.log('Base directory at ' + currentDir);