HymUiServer/server.js

58 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

2025-01-07 00:22:39 +00:00
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
const cors = require("cors");
app.use(cors());
const port = 6823;
// Function to help determine asset paths when using pkg
function getPublicPath() {
if (process.pkg) {
return path.join(path.dirname(process.execPath), 'web');
} else {
return path.join(__dirname, 'web');
}
}
const publicDirectory = getPublicPath();
app.use(express.static(publicDirectory));
// Middleware to parse JSON request bodies
app.use(express.json());
// Endpoint 1: Get address
app.get('/read-config', (req, res) => {
const filePath = path.join(path.dirname(process.execPath), 'ip_and_port.json');
if (fs.existsSync(filePath)) {
const data = fs.readFileSync(filePath, 'utf8');
const address = JSON.parse(data);
res.json(address);
} else {
res.json({});
}
});
// Endpoint 2: Save address
app.post('/update-config', (req, res) => {
const { ip, port } = req.body;
const ip_and_port = { ip, port };
const filePath = path.join(path.dirname(process.execPath), 'ip_and_port.json');
// Ensure the file exists and write data
fs.writeFileSync(filePath, JSON.stringify(ip_and_port, null, 2), 'utf8');
res.json({ message: 'Address saved successfully' });
});
// Catch-all to serve index.html for SPA routing
app.get('*', (req, res) => {
res.sendFile(path.join(publicDirectory, 'index.html'));
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});