Files
MagicMirror/js/server.js
Jboucly 961b3c96d6 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 <contact@jboucly.fr>
Co-authored-by: Kristjan ESPERANTO <35647502+KristjanESPERANTO@users.noreply.github.com>
2025-10-28 19:14:51 +01:00

145 lines
4.5 KiB
JavaScript

const fs = require("node:fs");
const http = require("node:http");
const https = require("node:https");
const path = require("node:path");
const express = require("express");
const helmet = require("helmet");
const socketio = require("socket.io");
const Log = require("logger");
const { cors, getConfig, getHtml, getVersion, getStartup, getEnvVars } = require("#server_functions");
const { ipAccessControl } = require(`${__dirname}/ip_access_control`);
const vendor = require(`${__dirname}/vendor`);
/**
* Server
* @param {object} config The MM config
* @class
*/
function Server (config) {
const app = express();
const port = process.env.MM_PORT || config.port;
const serverSockets = new Set();
let server = null;
/**
* Opens the server for incoming connections
* @returns {Promise} A promise that is resolved when the server listens to connections
*/
this.open = function () {
return new Promise((resolve) => {
if (config.useHttps) {
const options = {
key: fs.readFileSync(config.httpsPrivateKey),
cert: fs.readFileSync(config.httpsCertificate)
};
server = https.Server(options, app);
} else {
server = http.Server(app);
}
const io = socketio(server, {
cors: {
origin: /.*$/,
credentials: true
},
allowEIO3: true,
pingInterval: 120000, // server → client ping every 2 mins
pingTimeout: 120000 // wait up to 2 mins for client pong
});
server.on("connection", (socket) => {
serverSockets.add(socket);
socket.on("close", () => {
serverSockets.delete(socket);
});
});
Log.log(`Starting server on port ${port} ... `);
// Add explicit error handling BEFORE calling listen so we can give user-friendly feedback
server.once("error", (err) => {
if (err && err.code === "EADDRINUSE") {
const bindAddr = config.address || "localhost";
const portInUseMessage = [
"",
"────────────────────────────────────────────────────────────────",
` PORT IN USE: ${bindAddr}:${port}`,
"",
" Another process (most likely another MagicMirror instance)",
" is already using this port.",
"",
" Stop the other process (free the port) or use a different port.",
"────────────────────────────────────────────────────────────────"
].join("\n");
Log.error(portInUseMessage);
return;
}
Log.error("Failed to start server:", err);
});
server.listen(port, config.address || "localhost");
if (config.ipWhitelist instanceof Array && config.ipWhitelist.length === 0) {
Log.warn("You're using a full whitelist configuration to allow for all IPs");
}
app.use(ipAccessControl(config.ipWhitelist));
app.use(helmet(config.httpHeaders));
app.use("/js", express.static(__dirname));
let directories = ["/config", "/css", "/modules", "/node_modules/animate.css", "/node_modules/@fontsource", "/node_modules/@fortawesome", "/translations", "/tests/configs", "/tests/mocks"];
for (const [key, value] of Object.entries(vendor)) {
const dirArr = value.split("/");
if (dirArr[0] === "node_modules") directories.push(`/${dirArr[0]}/${dirArr[1]}`);
}
const uniqDirs = [...new Set(directories)];
for (const directory of uniqDirs) {
app.use(directory, express.static(path.resolve(global.root_path + directory)));
}
app.get("/cors", async (req, res) => await cors(req, res));
app.get("/version", (req, res) => getVersion(req, res));
app.get("/config", (req, res) => getConfig(req, res));
app.get("/startup", (req, res) => getStartup(req, res));
app.get("/env", (req, res) => getEnvVars(req, res));
app.get("/", (req, res) => getHtml(req, res));
// Reload endpoint for watch mode - triggers browser reload
app.get("/reload", (req, res) => {
Log.info("Reload request received, notifying all clients");
io.emit("RELOAD");
res.status(200).send("OK");
});
server.on("listening", () => {
resolve({
app,
io
});
});
});
};
/**
* Closes the server and destroys all lingering connections to it.
* @returns {Promise} A promise that resolves when server has successfully shut down
*/
this.close = function () {
return new Promise((resolve) => {
for (const socket of serverSockets.values()) {
socket.destroy();
}
server.close(resolve);
});
};
}
module.exports = Server;