|
| 1 | +const { spawn } = require("child_process"); |
| 2 | +const fs = require("fs"); |
| 3 | +const path = require("path"); |
| 4 | +const Log = require("../js/logger"); |
| 5 | + |
| 6 | +let child = null; |
| 7 | +let restartTimer = null; |
| 8 | + |
| 9 | +/** |
| 10 | + * Start the server process |
| 11 | + */ |
| 12 | +function startServer () { |
| 13 | + child = spawn("npm", ["run", "server"], { stdio: "inherit" }); |
| 14 | + |
| 15 | + child.on("exit", (code) => { |
| 16 | + Log.info(`Changes detected : ${code}`); |
| 17 | + Log.info("Restarting server..."); |
| 18 | + startServer(); |
| 19 | + }); |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Watch a directory for changes and restart the server on change |
| 24 | + * @param dir |
| 25 | + */ |
| 26 | +function watchDir (dir) { |
| 27 | + fs.watch(dir, { recursive: true }, (_eventType, filename) => { |
| 28 | + if (!filename) return; |
| 29 | + |
| 30 | + if (dir.includes("modules") && !filename.endsWith("node_helper.js")) return; |
| 31 | + |
| 32 | + if (restartTimer) clearTimeout(restartTimer); |
| 33 | + |
| 34 | + restartTimer = setTimeout(() => { |
| 35 | + Log.info(`Changes detected in ${dir}: ${filename} — restarting...`); |
| 36 | + if (child) child.kill("SIGTERM"); |
| 37 | + }, 500); |
| 38 | + }); |
| 39 | +} |
| 40 | + |
| 41 | +startServer(); |
| 42 | +watchDir(path.join(__dirname, "..", "config")); |
| 43 | +watchDir(path.join(__dirname, "..", "modules")); |
| 44 | + |
| 45 | +process.on("SIGINT", () => { |
| 46 | + if (restartTimer) clearTimeout(restartTimer); |
| 47 | + if (child) child.kill("SIGTERM"); |
| 48 | + process.exit(0); |
| 49 | +}); |
0 commit comments