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