-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
88 lines (76 loc) · 1.87 KB
/
server.js
File metadata and controls
88 lines (76 loc) · 1.87 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
'use strict';
const http = require('node:http');
const path = require('node:path');
const fs = require('node:fs');
const api = new Map();
const apiPath = './api/';
const cacheFile = (name) => {
const filePath = apiPath + name;
const key = path.basename(filePath, '.js');
try {
const libPath = require.resolve(filePath);
delete require.cache[libPath];
} catch {
return;
}
try {
const method = require(filePath);
api.set(key, method);
} catch {
api.delete(key);
}
};
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(apiPath);
watch(apiPath);
setTimeout(() => {
console.dir({ api });
}, 1000);
const receiveArgs = async (req) => {
const buffers = [];
for await (const chunk of req) buffers.push(chunk);
const data = Buffer.concat(buffers).toString();
return JSON.parse(data);
};
const httpError = (res, status, message) => {
res.statusCode = status;
res.end(`"${message}"`);
};
const controller = async (req, res) => {
const url = req.url === '/' ? '/index.html' : req.url;
const [first, second] = url.substring(1).split('/');
if (first === 'api') {
const method = api.get(second);
const args = await receiveArgs(req);
try {
const result = await method(...args);
if (!result) {
httpError(res, 500, 'Server error');
return;
}
res.end(JSON.stringify(result));
} catch (err) {
console.dir({ err });
httpError(res, 500, 'Server error');
}
} else {
const path = `./static/${first}`;
try {
const data = await fs.promises.readFile(path);
res.end(data);
} catch {
httpError(res, 404, 'File is not found');
}
}
};
http.createServer(controller).listen(8000);