48 lines
1.7 KiB
JavaScript
48 lines
1.7 KiB
JavaScript
const http = require("http");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
const PORT = process.env.PORT || 3000;
|
|
const DATA = path.join(__dirname, "data.json");
|
|
|
|
function readDb() {
|
|
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return { state: null }; }
|
|
}
|
|
function writeDb(db) {
|
|
fs.writeFileSync(DATA, JSON.stringify(db, null, 2));
|
|
}
|
|
function body(req) {
|
|
return new Promise((resolve) => {
|
|
let s = "";
|
|
req.on("data", (c) => (s += c));
|
|
req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); } });
|
|
});
|
|
}
|
|
|
|
const TYPES = { ".html": "text/html", ".css": "text/css", ".js": "application/javascript", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon" };
|
|
|
|
http.createServer(async (req, res) => {
|
|
const url = req.url.split("?")[0];
|
|
|
|
if (req.method === "GET" && url === "/api/state") {
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify(readDb().state || {}));
|
|
}
|
|
if (req.method === "POST" && url === "/api/state") {
|
|
const st = await body(req);
|
|
const db = readDb();
|
|
db.state = st;
|
|
writeDb(db);
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify({ ok: true }));
|
|
}
|
|
|
|
let file = url === "/" ? "/index.html" : url;
|
|
const full = path.join(__dirname, file);
|
|
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
|
|
res.writeHead(200, { "Content-Type": (TYPES[path.extname(full)] || "application/octet-stream") + "; charset=utf-8" });
|
|
return res.end(fs.readFileSync(full));
|
|
}
|
|
res.writeHead(404); res.end("Not found");
|
|
}).listen(PORT, () => console.log("Режим дня: сервер на порту " + PORT));
|