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 readData() { try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return { registrations: [] }; } } function writeData(d) { fs.writeFileSync(DATA, JSON.stringify(d, 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({}); } }); }); } function clean(v, max) { return String(v == null ? "" : v).replace(/[<>]/g, "").trim().slice(0, max); } http.createServer(async (req, res) => { const url = req.url.split("?")[0]; // API: список регистраций if (req.method === "GET" && url === "/api/registrations") { res.writeHead(200, { "Content-Type": "application/json" }); return res.end(JSON.stringify(readData().registrations)); } // API: регистрация if (req.method === "POST" && url === "/api/registrations") { const b = await body(req); const name = clean(b.name, 120); const dept = clean(b.dept, 120); const email = clean(b.email, 120); const phone = clean(b.phone, 40); if (!name || !dept || !email || !phone) { res.writeHead(400, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ ok: false, error: "Заполните все поля" })); } const rec = { name, dept, email, phone, createdAt: new Date().toISOString() }; const d = readData(); if (d.registrations.some((r) => r.email && r.email.toLowerCase() === email.toLowerCase())) { res.writeHead(409, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ ok: false, error: "С таким e-mail вы уже зарегистрированы" })); } d.registrations.push({ id: Date.now(), ...rec }); writeData(d); 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()) { const ext = path.extname(full); const type = ext === ".css" ? "text/css" : ext === ".js" ? "application/javascript" : "text/html"; res.writeHead(200, { "Content-Type": type + "; charset=utf-8" }); return res.end(fs.readFileSync(full)); } res.writeHead(404); res.end("Not found"); }).listen(PORT, () => console.log("Сервер на порту " + PORT));