proshu-sozdat-sportivnyy-say/server.js

25 lines
978 B
JavaScript

const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = process.env.PORT || 3000;
http.createServer((req, res) => {
let file = req.url === "/" ? "/index.html" : req.url.split("?")[0];
const decoded = decodeURIComponent(file);
const full = path.normalize(path.join(__dirname, decoded));
if (!full.startsWith(__dirname)) { res.writeHead(403); return res.end(); }
if (!fs.existsSync(full) || !fs.statSync(full).isFile()) { res.writeHead(404); return res.end("Not found"); }
const ext = path.extname(full).toLowerCase();
const type = {
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
}[ext] || "application/octet-stream";
res.writeHead(200, { "Content-Type": type + "; charset=utf-8" });
res.end(fs.readFileSync(full));
}).listen(PORT, () => console.log("Сервер на порту " + PORT));