-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdumbFileServer.js
298 lines (235 loc) · 8.03 KB
/
dumbFileServer.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import * as http from 'http';
import * as url from 'url';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import * as zlib from 'zlib';
// const g_address = process.argv[2] || '127.0.0.1';
const g_address = '0.0.0.0';
const g_port = parseInt(process.argv[3] || 9000, 10);
const worker_port = g_port;
const thread_port = g_port + 1;
const async_sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// maps file extention to MIME typere
const formatsMap = new Map([
[ '.ico', 'image/x-icon' ],
[ '.html', 'text/html' ],
[ '.js', 'text/javascript' ],
[ '.json', 'application/json' ],
[ '.css', 'text/css' ],
[ '.png', 'image/png' ],
[ '.jpg', 'image/jpeg' ],
[ '.wav', 'audio/wav' ],
[ '.mp3', 'audio/mpeg' ],
[ '.wav', 'audio/wav' ],
[ '.svg', 'image/svg+xml' ],
[ '.pdf', 'application/pdf' ],
[ '.doc', 'application/msword' ],
[ '.wasm', 'application/wasm' ],
]);
const build_folder_page = (req, parsedUrl, pathname) => {
const content = fs.readdirSync(pathname, { withFileTypes: true });
const allEntries = [];
const splittedPath = parsedUrl.pathname.split("/").filter(item => item.length > 0);
const isRoot = (splittedPath.length < 1);
const currFolder = isRoot ? '' : splittedPath.join("/");
console.log('isRoot', isRoot);
console.log(' currFolder ', currFolder);
// link to parent folder (if any)
if (!isRoot) {
const previousFolder = splittedPath.slice(0, splittedPath.length - 1).join("/");
const url = `http://${req.headers.host}/${previousFolder}`;
allEntries.push(`<a href="${url}"><b><= GO BACK</b></a>`);
}
const getUrl = (name) => {
return !isRoot ? `${currFolder}/${name}` : name;
}
const { folders, files } = content.reduce((acc, dirent) => {
if (dirent.isDirectory())
acc.folders.push({ url: getUrl(dirent.name), name: dirent.name });
else
acc.files.push({ url: getUrl(dirent.name), name: dirent.name });
return acc;
}, { folders: [], files: [] });
const allFolders = [];
for (const data of folders) {
allFolders.push(`<a href="http://${req.headers.host}/${data.url}"><b>${data.name}/</b></a>`);
}
const inputHtmlFiles = [];
const inputOtherFiles = [];
files.forEach((data) => {
if (path.parse(data.name).ext == '.html') {
inputHtmlFiles.push(data);
} else {
inputOtherFiles.push(data);
}
});
const allHtmlFiles = [];
for (const data of inputHtmlFiles) {
allHtmlFiles.push(`<a href="http://${req.headers.host}/${data.url}">${data.name}</a>`);
}
const allOtherFiles = [];
for (const data of inputOtherFiles) {
allOtherFiles.push(`<a href="http://${req.headers.host}/${data.url}">${data.name}</a>`);
}
return `
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>TEST</title>
<style>
body, a, li {
background-color: #0F0F0F;
border: 0px 0px 0px 0px;
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
font-family: arial;
color: #8F8F8F;
}
a:link { text-decoration: none; }
p, a {
margin-left: 10px;
}
ul {
line-height: 12px;
}
ul.big {
line-height: 30px;
font-size: 30px;
color: #8F0000;
}
ul.big a {
line-height: 30px;
font-size: 30px;
color: #BB8888;
}
</style>
</head>
<body>
<p>=> <root>/${currFolder}</p>
${allEntries.map(line => ` <b>${line}</b>`).join("<br>")}
<p>FOLDERS (${allFolders.length})</p>
<ul>
${allFolders.map(line => ` <li>${line}</li>`).join("<br>")}
</ul>
<p>FILES (${files.length})</p>
<ul class="big">
${allHtmlFiles.map(line => ` <li>=> ${line}</li>`).join("<br>")}
</ul>
<ul>
${allOtherFiles.map(line => ` <li>${line}</li>`).join("<br>")}
</ul>
</body>
</html>
`;
}
const on_file_request = async (threading_headers, req, res) => {
// parse URL
const parsedUrl = url.parse(req.url);
// extract URL path
let pathname = `.${parsedUrl.pathname}`;
// based on the URL path, extract the file extention. e.g. .js, .doc, ...
const ext = path.parse(pathname).ext;
if (!fs.existsSync(pathname)) {
// if the file is not found, return 404
res.statusCode = 404;
res.end(`File "${pathname}" not found!`);
return;
}
let data;
// if it is a directory: list it's content
const fileStats = fs.statSync(pathname);
if (fileStats.isDirectory()) {
data = build_folder_page(req, parsedUrl, pathname);
res.setHeader('Content-type', "text/html");
res.setHeader('Last-Modified', (new Date()).toString());
}
else {
// read file from file system
data = fs.readFileSync(pathname);
res.setHeader('Content-type', formatsMap.get(ext) || "text/plain");
res.setHeader('Last-Modified', fileStats.mtime.toString());
}
const originalSize = data.length;
let sizeToSend = originalSize;
if (
req.headers['accept-encoding'] &&
req.headers['accept-encoding'].indexOf("gzip") >= 0
) {
res.setHeader('Content-Encoding', "gzip" );
data = zlib.gzipSync(data);
}
sizeToSend = data.length;
// // attempt at preventing browser caching (for debug)
// res.setHeader('Last-Modified', (new Date()).toString());
if (threading_headers === true) {
res.setHeader('Cross-Origin-Opener-Policy', "same-origin");
res.setHeader('Cross-Origin-Embedder-Policy', "require-corp");
}
// await async_sleep(500);
let logMsg = `${req.method} ${req.url} ${sizeToSend / 1000}Kb`;
if (sizeToSend < originalSize)
logMsg += ` (${originalSize / 1000}Kb, ${(originalSize / sizeToSend).toFixed(1)}x)`;
console.log(logMsg);
res.end(data);
}
// useful to test on local WiFi with a smartphone
const list_WiFi_IpAddresses = (inPort) => {
// const allInterfaces = [];
const allInterfaces = new Map();
const interfaces = os.networkInterfaces();
Object.keys(interfaces).forEach((networkName) => {
interfaces[networkName].forEach((iface) => {
const family = iface.family.toLowerCase() || '{unknown}';
// family -> network name
let currNetwork = allInterfaces.get(family);
if (currNetwork == undefined) {
currNetwork = new Map();
allInterfaces.set(family, currNetwork);
}
// network name -> url
let currUrls = currNetwork.get(networkName);
if (currUrls == undefined) {
currUrls = [];
currNetwork.set(networkName, currUrls);
}
currUrls.push(`http://${iface.address}:${inPort}/`);
});
});
const ipv4Interfaces = [];
allInterfaces.forEach((currNetwork, family) => {
if (family === 'ipv4')
ipv4Interfaces.push(currNetwork);
});
let longestNetworkNameLength = 0;
ipv4Interfaces.forEach((currNetwork) => {
currNetwork.forEach((currUrls, networkName) => {
longestNetworkNameLength = Math.max(longestNetworkNameLength, networkName.length);
});
});
longestNetworkNameLength = Math.min(150, longestNetworkNameLength);
const separator = "".padStart(longestNetworkNameLength, ' ');
ipv4Interfaces.forEach((currNetwork) => {
currNetwork.forEach((currUrls, networkName) => {
// console.log();
// console.log(` => network: ${networkName}`);
currUrls.forEach((url) => {
console.log(` => network: ${networkName.padStart(longestNetworkNameLength)}, ${url}`);
// console.log(` ---> ${url}`);
});
});
});
console.log();
};
const make_server = (inPort, threading_headers) => {
http.createServer((req, res) => on_file_request(threading_headers, req, res))
.listen(inPort, g_address, () => {
console.log(`Server listening`);
console.log(`=> http://127.0.0.1:${inPort}/`);
list_WiFi_IpAddresses(inPort);
});
};
make_server(worker_port, false);
make_server(thread_port, true);