sozday-analiz-rashodov-s-uka/server.js

61 lines
2.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Временная точка проверки: валидация script.js + data.json при старте.
try {
require("./script.js");
} catch (e) {
console.error("SYNTAX-FAIL script.js: " + e.message);
process.exit(1);
}
try {
const d = require("./data.json");
if (!Array.isArray(d.rows) || !d.rows.length) throw new Error("data.json: нет rows");
const n = d.rows.length;
const t25 = d.rows.reduce((a, r) => a + (r.y2025 || 0), 0);
console.log("CHECK: syntax OK, data.json rows: " + n + ", 2025 total: " + Math.round(t25).toLocaleString("ru-RU"));
} catch (e) {
console.error("DATA-FAIL: " + e.message);
process.exit(1);
}
const http = require("http");
const fs = require("fs");
const path = require("path");
const srv = http.createServer((req, res) => {
const url = req.url.split("?")[0];
if (url === "/" || url === "/index.html") {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
return fs.createReadStream(path.join(__dirname, "index.html")).pipe(res);
}
if (url === "/presentation.html") {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
return fs.createReadStream(path.join(__dirname, "presentation.html")).pipe(res);
}
if (url === "/data.json") {
res.writeHead(200, { "Content-Type": "application/json" });
return fs.createReadStream(path.join(__dirname, "data.json")).pipe(res);
}
// Отчёт — xlsx/docx. Отдаём как приложение, чтобы браузер скачал, а не попробовал показать.
const m = url.match(/^\/([^\/]+\.(xlsx|docx|csv|json|html|js|css))/i);
if (m) {
const file = path.basename(decodeURIComponent(m[1]));
const fp = path.join(__dirname, file);
if (fs.existsSync(fp)) {
const ct =
file.toLowerCase().endsWith(".xlsx") ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" :
file.toLowerCase().endsWith(".docx") ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" :
file.toLowerCase().endsWith(".csv") ? "text/csv; charset=utf-8" :
file.toLowerCase().endsWith(".json") ? "application/json" :
file.toLowerCase().endsWith(".js") ? "text/javascript" :
file.toLowerCase().endsWith(".css") ? "text/css" : "text/html";
res.writeHead(200, {
"Content-Type": ct,
"Content-Disposition": 'attachment; filename="' + encodeURIComponent(file) + '"'
});
return fs.createReadStream(fp).pipe(res);
}
}
res.writeHead(404);
res.end("not found");
});
srv.listen(process.env.PORT || 3000, () => {
console.log("server on port " + (process.env.PORT || 3000));
});