Files
self-hoested-media-tracker/server.js
2026-07-17 10:00:37 +01:00

51 lines
1.2 KiB
JavaScript

const http = require("http");
const fs = require("fs");
const path = require("path");
const root = __dirname;
const port = Number(process.env.PORT || 5173);
const contentTypes = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
};
const server = http.createServer((request, response) => {
const urlPath = getUrlPath(request.url);
const requestedPath = urlPath === "/" ? "/index.html" : urlPath;
const filePath = path.resolve(root, `.${requestedPath}`);
if (!filePath.startsWith(root)) {
response.writeHead(403);
response.end("Forbidden");
return;
}
fs.readFile(filePath, (error, data) => {
if (error) {
response.writeHead(404);
response.end("Not found");
return;
}
response.writeHead(200, {
"Content-Type": contentTypes[path.extname(filePath)] || "application/octet-stream",
});
response.end(data);
});
});
server.listen(port, () => {
console.log(`Media Tracker running at http://localhost:${port}`);
});
function getUrlPath(value) {
try {
return decodeURIComponent(new URL(value, "http://localhost").pathname);
} catch (error) {
return "/";
}
}