-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
63 lines (55 loc) · 1.25 KB
/
server.js
File metadata and controls
63 lines (55 loc) · 1.25 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
'use strict';
const fs = require('node:fs');
const http = require('node:http');
const cache = new Map();
const lib = './lib/';
const cacheFile = (path) => {
const filePath = lib + path;
try {
const libPath = require.resolve(filePath);
delete require.cache[libPath];
} catch (e) {
return;
}
try {
const mod = require(filePath);
cache.set(path, mod);
} catch (e) {
cache.delete(path);
}
};
const cacheFolder = (path) => {
fs.readdir(path, (err, files) => {
if (err) return;
files.forEach(cacheFile);
});
};
const watch = (path) => {
fs.watch(path, (event, file) => {
cacheFile(file);
});
};
cacheFolder(lib);
watch(lib);
const ls = (res, list) => {
res.write('<html>');
for (const name of list) {
res.write(`<li><a href="${name}/">${name}</li>`);
}
res.end('</html>');
};
http.createServer((req, res) => {
const url = req.url.substring(1);
if (!url) return ls(res, cache.keys());
const [mod, method] = url.split('/');
const methods = cache.get(mod);
if (methods) {
if (!method) return ls(res, Object.keys(methods));
const handler = methods[method];
if (handler) {
res.end(handler().toString());
return;
}
}
res.end('File ' + url + 'not found');
}).listen(8000);