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 readItems() { try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return []; } } function writeItems(items) { fs.writeFileSync(DATA, JSON.stringify(items, 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({}); } }); }); } http.createServer(async (req, res) => { const url = req.url.split("?")[0]; // CORS headers res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type"); if (req.method === "OPTIONS") { res.writeHead(200); return res.end(); } // API: get all items if (req.method === "GET" && url === "/api/items") { res.writeHead(200, { "Content-Type": "application/json" }); return res.end(JSON.stringify(readItems())); } // API: add single item if (req.method === "POST" && url === "/api/items") { const data = await body(req); const items = readItems(); // If data is array, replace all items if (Array.isArray(data)) { writeItems(data); } else { // If data is single item, add it const newItem = { id: Date.now(), ...data }; items.push(newItem); writeItems(items); } res.writeHead(200, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ ok: true })); } // Static files 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" : ext === ".svg" ? "image/svg+xml" : "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));