-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (53 loc) · 1.53 KB
/
Copy pathserver.js
File metadata and controls
62 lines (53 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
const PORT = process.env.PORT || 3000;
const DATA_DIR = process.env.DATA_DIR || __dirname;
const DATA_FILE = path.join(DATA_DIR, "data.json");
// Ensure data directory exists
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
app.use(express.json({ limit: "1mb" }));
// Load data from file
function loadData() {
try {
if (fs.existsSync(DATA_FILE)) {
return JSON.parse(fs.readFileSync(DATA_FILE, "utf8"));
}
} catch (e) {
console.error("Error reading data file:", e.message);
}
return { players: [] };
}
// Save data to file
function saveData(data) {
fs.writeFileSync(DATA_FILE, JSON.stringify(data), "utf8");
}
// Serve the HTML file
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
// GET /api/state — read the current state
app.get("/api/state", (req, res) => {
const data = loadData();
res.json(data);
});
// POST /api/state — save the state (requires admin token in query)
app.post("/api/state", (req, res) => {
const token = req.query.token;
if (token !== "runni123") {
return res.status(403).json({ error: "Forbidden" });
}
const newData = req.body;
if (!newData || !newData.players) {
return res.status(400).json({ error: "Invalid data" });
}
saveData(newData);
res.json({ ok: true });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Data directory: ${DATA_DIR}`);
});