|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const http = require('http'); |
| 4 | +const path = require('path'); |
| 5 | +const fs = require('fs'); |
| 6 | +const Websocket = require('websocket').server; |
| 7 | + |
| 8 | +global.memory = new Map(); |
| 9 | +const api = new Map(); |
| 10 | + |
| 11 | +const apiPath = './api/'; |
| 12 | + |
| 13 | +const cacheFile = name => { |
| 14 | + const filePath = apiPath + name; |
| 15 | + const key = path.basename(filePath, '.js'); |
| 16 | + try { |
| 17 | + const libPath = require.resolve(filePath); |
| 18 | + delete require.cache[libPath]; |
| 19 | + } catch (e) { |
| 20 | + return; |
| 21 | + } |
| 22 | + try { |
| 23 | + const method = require(filePath); |
| 24 | + api.set(key, method); |
| 25 | + } catch (e) { |
| 26 | + api.delete(name); |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +const cacheFolder = path => { |
| 31 | + fs.readdir(path, (err, files) => { |
| 32 | + if (err) return; |
| 33 | + files.forEach(cacheFile); |
| 34 | + }); |
| 35 | +}; |
| 36 | + |
| 37 | +const watch = path => { |
| 38 | + fs.watch(path, (event, file) => { |
| 39 | + cacheFile(file); |
| 40 | + }); |
| 41 | +}; |
| 42 | + |
| 43 | +cacheFolder(apiPath); |
| 44 | +watch(apiPath); |
| 45 | + |
| 46 | +setTimeout(() => { |
| 47 | + console.dir({ api }); |
| 48 | +}, 1000); |
| 49 | + |
| 50 | +const server = http.createServer(async (req, res) => { |
| 51 | + const url = req.url === '/' ? '/index.html' : req.url; |
| 52 | + const [file] = url.substring(1).split('/'); |
| 53 | + const path = `./static/${file}`; |
| 54 | + try { |
| 55 | + const data = await fs.promises.readFile(path); |
| 56 | + res.end(data); |
| 57 | + } catch (err) { |
| 58 | + res.statusCode = 404; |
| 59 | + res.end('"File is not found"'); |
| 60 | + } |
| 61 | +}).listen(8000); |
| 62 | + |
| 63 | +const ws = new Websocket({ |
| 64 | + httpServer: server, |
| 65 | + autoAcceptConnections: false |
| 66 | +}); |
| 67 | + |
| 68 | +ws.on('request', req => { |
| 69 | + const connection = req.accept('', req.origin); |
| 70 | + console.log('Connected ' + connection.remoteAddress); |
| 71 | + connection.on('message', async message => { |
| 72 | + const dataName = message.type + 'Data'; |
| 73 | + const data = message[dataName]; |
| 74 | + console.log('Received: ' + data); |
| 75 | + const obj = JSON.parse(data); |
| 76 | + const { method, args } = obj; |
| 77 | + const fn = api.get(method); |
| 78 | + try { |
| 79 | + const result = await fn(...args); |
| 80 | + if (!result) { |
| 81 | + connection.send('"No result"'); |
| 82 | + return; |
| 83 | + } |
| 84 | + connection.send(JSON.stringify(result)); |
| 85 | + } catch (err) { |
| 86 | + console.dir({ err }); |
| 87 | + connection.send('"Server error"'); |
| 88 | + } |
| 89 | + }); |
| 90 | +}); |
0 commit comments