const http = require("http"); const fs = require("fs"); const path = require("path"); const PORT = 3000; const ROOT = __dirname; const MIME = { ".html": "text/html", ".js": "application/javascript", ".json": "application/json", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", }; const server = http.createServer((req, res) => { let filePath = path.join(ROOT, req.url === "/" ? "index.html" : req.url); filePath = path.normalize(filePath); if (!filePath.startsWith(ROOT)) { res.writeHead(403); return res.end("Forbidden"); } const ext = path.extname(filePath); const contentType = MIME[ext] || "application/octet-stream"; fs.readFile(filePath, (err, data) => { if (err) { res.writeHead(404); return res.end("Not found"); } res.writeHead(200, { "Content-Type": contentType }); res.end(data); }); }); server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });