-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
85 lines (73 loc) · 1.84 KB
/
server.js
File metadata and controls
85 lines (73 loc) · 1.84 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
'use strict';
const http = require('node:http');
const path = require('node:path');
const fs = require('node:fs');
const WebSocket = require('ws');
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 controller = async (req, res) => {
const url = req.url === '/' ? '/index.html' : req.url;
const [file] = url.substring(1).split('/');
const path = `./static/${file}`;
try {
const data = await fs.promises.readFile(path);
res.end(data);
} catch {
res.statusCode = 404;
res.end('"File is not found"');
}
};
const server = http.createServer(controller).listen(8000);
const ws = new WebSocket.Server({ server });
ws.on('connection', (connection, req) => {
console.log('Connected ' + req.socket.remoteAddress);
connection.on('message', async (message) => {
console.log('Received: ' + message);
const obj = JSON.parse(message);
const { method, args } = obj;
const fn = api.get(method);
try {
const result = await fn(...args);
if (!result) {
connection.send('"No result"');
return;
}
connection.send(JSON.stringify(result));
} catch (err) {
console.dir({ err });
connection.send('"Server error"');
}
});
});