Skip to content

Commit 062bc8e

Browse files
committed
Example with autoreload and introspection
1 parent a833dd9 commit 062bc8e

4 files changed

Lines changed: 82 additions & 0 deletions

File tree

JavaScript/lib/submodule1.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
'use strict';
2+
3+
const method11 = () => 11;
4+
const method12 = () => 12;
5+
6+
module.exports = { method11, method12 };

JavaScript/lib/submodule2.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
'use strict';
2+
3+
const method21 = () => 21;
4+
const method22 = () => 22;
5+
const method23 = () => 23;
6+
7+
module.exports = { method21, method22, method23 };

JavaScript/lib/submodule3.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
'use strict';
2+
3+
const method31 = () => 31;
4+
const method32 = () => 32;
5+
6+
module.exports = { method31, method32 };

JavaScript/server.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
'use strict';
2+
3+
const fs = require('fs');
4+
const http = require('http');
5+
6+
const cache = new Map();
7+
const lib = './lib/';
8+
9+
const cacheFile = (path) => {
10+
const filePath = lib + path;
11+
try {
12+
const libPath = require.resolve(filePath);
13+
delete require.cache[libPath];
14+
} catch (e) {
15+
return;
16+
}
17+
try {
18+
const mod = require(filePath);
19+
cache.set(path, mod);
20+
} catch (e) {
21+
cache.delete(path);
22+
}
23+
};
24+
25+
const cacheFolder = (path) => {
26+
fs.readdir(path, (err, files) => {
27+
if (err) return;
28+
files.forEach(cacheFile);
29+
});
30+
};
31+
32+
const watch = (path) => {
33+
fs.watch(path, (event, file) => {
34+
cacheFile(file);
35+
});
36+
};
37+
38+
cacheFolder(lib);
39+
watch(lib);
40+
41+
const ls = (res, list) => {
42+
res.write('<html>');
43+
for (const name of list) {
44+
res.write(`<li><a href="${name}/">${name}</li>`);
45+
}
46+
res.end('</html>');
47+
};
48+
49+
http.createServer((req, res) => {
50+
const url = req.url.substring(1);
51+
if (!url) return ls(res, cache.keys());
52+
const [mod, method] = url.split('/');
53+
const methods = cache.get(mod);
54+
if (methods) {
55+
if (!method) return ls(res, Object.keys(methods));
56+
const handler = methods[method];
57+
if (handler) {
58+
res.end(handler().toString());
59+
return;
60+
}
61+
}
62+
res.end('File ' + url + 'not found');
63+
}).listen(8000);

0 commit comments

Comments
 (0)