Skip to content

Commit 961b3c9

Browse files
jbouclyJbouclyKristjanESPERANTO
authored
feat(core): add server:watch script with automatic restart on file changes (#3920)
## Description This PR adds a new `server:watch` script that runs MagicMirror² in server-only mode with automatic restart and browser reload capabilities. Particularly helpful for: - **Developers** who need to see changes immediately without manual restarts. - **Users setting up their mirror** who make many changes to `config.js` or `custom.css` and need quick feedback. ### What it does When you run `npm run server:watch`, the watcher monitors files you specify in `config.watchTargets`. Whenever a monitored file changes: 1. The server automatically restarts 2. Waits for the port to become available 3. Sends a reload notification to all connected browsers via Socket.io 4. Browsers automatically refresh to show the changes This creates a seamless development experience where you can edit code, save, and see the results within seconds. ### Implementation highlights **Zero dependencies:** Uses only Node.js built-ins (`fs.watch`, `child_process.spawn`, `net`, `http`) - no nodemon or external watchers needed. **Smart file watching:** Monitors parent directories instead of files directly to handle atomic writes from modern editors (VSCode, etc.) that create temporary files during save operations. **Port management:** Waits for the old server instance to fully release the port before starting a new one, preventing "port already in use" errors. ### Configuration Users explicitly define which files to monitor in their `config.js`: ```js let config = { watchTargets: [ "config/config.js", "css/custom.css", "modules/MMM-MyModule/MMM-MyModule.js", "modules/MMM-MyModule/node_helper.js" ], // ... rest of config }; ``` This explicit approach keeps the implementation simple (~260 lines) while giving users full control over what triggers restarts. If `watchTargets` is empty or undefined, the watcher starts but monitors nothing, logging a clear warning message. --- **Note:** This PR description has been updated to reflect the final implementation. During the review process, we refined the approach multiple times based on feedback. --------- Co-authored-by: Jboucly <[email protected]> Co-authored-by: Kristjan ESPERANTO <[email protected]>
1 parent 2e795f6 commit 961b3c9

File tree

7 files changed

+304
-4
lines changed

7 files changed

+304
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ planned for 2026-01-01
1414
### Added
1515

1616
- [weather] feat: add configurable forecast date format option (#3918)
17+
- [core] Add new `server:watch` script to run MagicMirror² server-only with automatic restarts when files (defined in `config.watchTargets`) change (#3920)
1718

1819
### Changed
1920

js/app.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const Utils = require(`${__dirname}/utils`);
1515
const defaultModules = require(`${global.root_path}/modules/default/defaultmodules`);
1616
// used to control fetch timeout for node_helpers
1717
const { setGlobalDispatcher, Agent } = require("undici");
18-
const { getEnvVarsAsObj } = require("#server_functions");
18+
const { getEnvVarsAsObj, getConfigFilePath } = require("#server_functions");
1919
// common timeout value, provide environment override in case
2020
const fetch_timeout = process.env.mmFetchTimeout !== undefined ? process.env.mmFetchTimeout : 30000;
2121

@@ -72,7 +72,7 @@ function App () {
7272

7373
// For this check proposed to TestSuite
7474
// https://forum.magicmirror.builders/topic/1456/test-suite-for-magicmirror/8
75-
const configFilename = path.resolve(global.configuration_file || `${global.root_path}/config/config.js`);
75+
const configFilename = getConfigFilePath();
7676
let templateFile = `${configFilename}.template`;
7777

7878
// check if templateFile exists

js/main.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/* global Loader, defaults, Translator, addAnimateCSS, removeAnimateCSS, AnimateCSSIn, AnimateCSSOut, modulePositions */
1+
/* global Loader, defaults, Translator, addAnimateCSS, removeAnimateCSS, AnimateCSSIn, AnimateCSSOut, modulePositions, io */
22

33
const MM = (function () {
44
let modules = [];
@@ -605,6 +605,18 @@ const MM = (function () {
605605

606606
createDomObjects();
607607

608+
// Setup global socket listener for RELOAD event (watch mode)
609+
if (typeof io !== "undefined") {
610+
const socket = io("/", {
611+
path: `${config.basePath || "/"}socket.io`
612+
});
613+
614+
socket.on("RELOAD", () => {
615+
Log.warn("Reload notification received from server");
616+
window.location.reload(true);
617+
});
618+
}
619+
608620
if (config.reloadAfterServerRestart) {
609621
setInterval(async () => {
610622
// if server startup time has changed (which means server was restarted)

js/server.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,13 @@ function Server (config) {
111111

112112
app.get("/", (req, res) => getHtml(req, res));
113113

114+
// Reload endpoint for watch mode - triggers browser reload
115+
app.get("/reload", (req, res) => {
116+
Log.info("Reload request received, notifying all clients");
117+
io.emit("RELOAD");
118+
res.status(200).send("OK");
119+
});
120+
114121
server.on("listening", () => {
115122
resolve({
116123
app,

js/server_functions.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,4 +176,22 @@ function getEnvVars (req, res) {
176176
res.send(obj);
177177
}
178178

179-
module.exports = { cors, getConfig, getHtml, getVersion, getStartup, getEnvVars, getEnvVarsAsObj, getUserAgent };
179+
/**
180+
* Get the config file path from environment or default location
181+
* @returns {string} The absolute config file path
182+
*/
183+
function getConfigFilePath () {
184+
// Ensure root_path is set (for standalone contexts like watcher)
185+
if (!global.root_path) {
186+
global.root_path = path.resolve(`${__dirname}/../`);
187+
}
188+
189+
// Check environment variable if global not set
190+
if (!global.configuration_file && process.env.MM_CONFIG_FILE) {
191+
global.configuration_file = process.env.MM_CONFIG_FILE;
192+
}
193+
194+
return path.resolve(global.configuration_file || `${global.root_path}/config/config.js`);
195+
}
196+
197+
module.exports = { cors, getConfig, getHtml, getVersion, getStartup, getEnvVars, getEnvVarsAsObj, getUserAgent, getConfigFilePath };

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
"lint:prettier": "prettier . --write",
4444
"prepare": "[ -f node_modules/.bin/husky ] && husky || echo no husky installed.",
4545
"server": "node ./serveronly",
46+
"server:watch": "node ./serveronly/watcher.js",
4647
"start": "node --run start:x11",
4748
"start:dev": "node --run start:x11 -- dev",
4849
"start:wayland": "WAYLAND_DISPLAY=\"${WAYLAND_DISPLAY:=wayland-1}\" ./node_modules/.bin/electron js/electron.js --enable-features=UseOzonePlatform --ozone-platform=wayland",

serveronly/watcher.js

Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
// Load lightweight internal alias resolver to enable require("logger")
2+
require("../js/alias-resolver");
3+
4+
const { spawn } = require("child_process");
5+
const fs = require("fs");
6+
const path = require("path");
7+
const net = require("net");
8+
const http = require("http");
9+
const Log = require("logger");
10+
const { getConfigFilePath } = require("#server_functions");
11+
12+
const RESTART_DELAY_MS = 500;
13+
const PORT_CHECK_MAX_ATTEMPTS = 20;
14+
const PORT_CHECK_INTERVAL_MS = 500;
15+
16+
let child = null;
17+
let restartTimer = null;
18+
let isShuttingDown = false;
19+
let isRestarting = false;
20+
let serverConfig = null;
21+
const rootDir = path.join(__dirname, "..");
22+
23+
/**
24+
* Get the server configuration (port and address)
25+
* @returns {{port: number, address: string}} The server config
26+
*/
27+
function getServerConfig () {
28+
if (serverConfig) return serverConfig;
29+
30+
try {
31+
const configPath = getConfigFilePath();
32+
delete require.cache[require.resolve(configPath)];
33+
const config = require(configPath);
34+
serverConfig = {
35+
port: global.mmPort || config.port || 8080,
36+
address: config.address || "localhost"
37+
};
38+
} catch (err) {
39+
serverConfig = { port: 8080, address: "localhost" };
40+
}
41+
42+
return serverConfig;
43+
}
44+
45+
/**
46+
* Check if a port is available on the configured address
47+
* @param {number} port The port to check
48+
* @returns {Promise<boolean>} True if port is available
49+
*/
50+
function isPortAvailable (port) {
51+
return new Promise((resolve) => {
52+
const server = net.createServer();
53+
54+
server.once("error", () => {
55+
resolve(false);
56+
});
57+
58+
server.once("listening", () => {
59+
server.close();
60+
resolve(true);
61+
});
62+
63+
// Use the same address as the actual server will bind to
64+
const { address } = getServerConfig();
65+
server.listen(port, address);
66+
});
67+
}
68+
69+
/**
70+
* Wait until port is available
71+
* @param {number} port The port to wait for
72+
* @param {number} maxAttempts Maximum number of attempts
73+
* @returns {Promise<void>}
74+
*/
75+
async function waitForPort (port, maxAttempts = PORT_CHECK_MAX_ATTEMPTS) {
76+
for (let i = 0; i < maxAttempts; i++) {
77+
if (await isPortAvailable(port)) {
78+
Log.info(`Port ${port} is now available`);
79+
return;
80+
}
81+
await new Promise((resolve) => setTimeout(resolve, PORT_CHECK_INTERVAL_MS));
82+
}
83+
Log.warn(`Port ${port} still not available after ${maxAttempts} attempts`);
84+
}
85+
86+
/**
87+
* Start the server process
88+
*/
89+
function startServer () {
90+
// Start node directly instead of via npm to avoid process tree issues
91+
child = spawn("node", ["./serveronly"], {
92+
stdio: "inherit",
93+
cwd: path.join(__dirname, "..")
94+
});
95+
96+
child.on("error", (error) => {
97+
Log.error("Failed to start server process:", error.message);
98+
child = null;
99+
});
100+
101+
child.on("exit", (code, signal) => {
102+
child = null;
103+
104+
if (isShuttingDown) {
105+
return;
106+
}
107+
108+
if (isRestarting) {
109+
// Expected restart - don't log as error
110+
isRestarting = false;
111+
} else {
112+
// Unexpected exit
113+
Log.error(`Server exited unexpectedly with code ${code} and signal ${signal}`);
114+
}
115+
});
116+
}
117+
118+
/**
119+
* Send reload notification to all connected clients
120+
*/
121+
function notifyClientsToReload () {
122+
const { port, address } = getServerConfig();
123+
const options = {
124+
hostname: address,
125+
port: port,
126+
path: "/reload",
127+
method: "GET"
128+
};
129+
130+
const req = http.request(options, (res) => {
131+
if (res.statusCode === 200) {
132+
Log.info("Reload notification sent to clients");
133+
}
134+
});
135+
136+
req.on("error", (err) => {
137+
// Server might not be running yet, ignore
138+
Log.debug(`Could not send reload notification: ${err.message}`);
139+
});
140+
141+
req.end();
142+
}
143+
144+
/**
145+
* Restart the server process
146+
* @param {string} reason The reason for the restart
147+
*/
148+
async function restartServer (reason) {
149+
if (restartTimer) clearTimeout(restartTimer);
150+
151+
restartTimer = setTimeout(async () => {
152+
Log.info(reason);
153+
154+
if (child) {
155+
isRestarting = true;
156+
157+
// Get the actual port being used
158+
const { port } = getServerConfig();
159+
160+
// Notify clients to reload before restart
161+
notifyClientsToReload();
162+
163+
// Set up one-time listener for the exit event
164+
child.once("exit", async () => {
165+
// Wait until port is actually available
166+
await waitForPort(port);
167+
// Reset config cache in case it changed
168+
serverConfig = null;
169+
startServer();
170+
});
171+
172+
child.kill("SIGTERM");
173+
} else {
174+
startServer();
175+
}
176+
}, RESTART_DELAY_MS);
177+
}
178+
179+
/**
180+
* Watch a specific file for changes and restart the server on change
181+
* Watches the parent directory to handle editors that use atomic writes
182+
* @param {string} file The file path to watch
183+
*/
184+
function watchFile (file) {
185+
try {
186+
const fileName = path.basename(file);
187+
const dirName = path.dirname(file);
188+
189+
const watcher = fs.watch(dirName, (_eventType, changedFile) => {
190+
// Only trigger for the specific file we're interested in
191+
if (changedFile !== fileName) return;
192+
193+
Log.info(`[watchFile] Change detected in: ${file}`);
194+
if (restartTimer) clearTimeout(restartTimer);
195+
196+
restartTimer = setTimeout(() => {
197+
Log.info(`[watchFile] Triggering restart due to change in: ${file}`);
198+
restartServer(`File changed: ${path.basename(file)} — restarting...`);
199+
}, RESTART_DELAY_MS);
200+
});
201+
202+
watcher.on("error", (error) => {
203+
Log.error(`Watcher error for ${file}:`, error.message);
204+
});
205+
206+
Log.log(`Watching file: ${file}`);
207+
} catch (error) {
208+
Log.error(`Failed to watch file ${file}:`, error.message);
209+
}
210+
}
211+
212+
startServer();
213+
214+
// Setup file watching based on config
215+
try {
216+
const configPath = getConfigFilePath();
217+
delete require.cache[require.resolve(configPath)];
218+
const config = require(configPath);
219+
220+
let watchTargets = [];
221+
if (Array.isArray(config.watchTargets) && config.watchTargets.length > 0) {
222+
watchTargets = config.watchTargets.filter((target) => typeof target === "string" && target.trim() !== "");
223+
}
224+
225+
if (watchTargets.length === 0) {
226+
Log.warn("Watch mode is enabled but no watchTargets are configured. No files will be monitored. Set the watchTargets array in your config.js to enable file watching.");
227+
}
228+
229+
Log.log(`Watch mode enabled. Watching ${watchTargets.length} file(s)`);
230+
231+
// Watch each target file
232+
for (const target of watchTargets) {
233+
const targetPath = path.isAbsolute(target)
234+
? target
235+
: path.join(rootDir, target);
236+
237+
// Check if file exists
238+
if (!fs.existsSync(targetPath)) {
239+
Log.warn(`Watch target does not exist: ${targetPath}`);
240+
continue;
241+
}
242+
243+
// Check if it's a file (directories are not supported)
244+
const stats = fs.statSync(targetPath);
245+
if (stats.isFile()) {
246+
watchFile(targetPath);
247+
} else {
248+
Log.warn(`Watch target is not a file (directories not supported): ${targetPath}`);
249+
}
250+
}
251+
} catch (err) {
252+
// Config file might not exist or be invalid, use fallback targets
253+
Log.warn("Could not load watchTargets from config.");
254+
}
255+
256+
process.on("SIGINT", () => {
257+
isShuttingDown = true;
258+
if (restartTimer) clearTimeout(restartTimer);
259+
if (child) child.kill("SIGTERM");
260+
process.exit(0);
261+
});

0 commit comments

Comments
 (0)