Files
speedcode/index.js
T
2026-04-04 11:32:43 -05:00

105 lines
2.7 KiB
JavaScript

const http = require("http");
const fs = require("fs");
const path = require("path");
const { createLogger, format, transports } = require("winston");
const { consoleFormat } = require("winston-console-format");
const util = require("util");
const logger = createLogger({
level: "silly",
format: format.combine(
format.timestamp(),
format.ms(),
format.errors({ stack: true }),
format.splat(),
format.json()
),
defaultMeta: { service: "Test" },
transports: [
new transports.Console({
format: format.combine(
format.colorize({ all: true }),
format.padLevels(),
consoleFormat({
showMeta: true,
metaStrip: ["timestamp", "service"],
inspectOptions: {
depth: Infinity,
colors: true,
maxArrayLength: Infinity,
breakLength: 120,
compact: Infinity,
},
})
),
}),
],
});
const PORT = process.env.PORT || 3000;
const PUBLIC_DIR = path.join(__dirname, "public");
const MIME_TYPES = {
".html": "text/html; charset=UTF-8",
".css": "text/css; charset=UTF-8",
".js": "application/javascript; charset=UTF-8",
".json": "application/json; charset=UTF-8",
".svg": "image/svg+xml",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".ico": "image/x-icon"
};
function resolveFilePath(urlPath) {
if (!urlPath || urlPath === "/") {
return path.join(PUBLIC_DIR, "index.html");
}
const safePath = path.normalize(urlPath).replace(/^(\.\.([/\\]|$))+/, "");
return path.join(PUBLIC_DIR, safePath);
}
function sendFile(filePath, res) {
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code === "ENOENT") {
res.writeHead(404, { "Content-Type": "text/plain; charset=UTF-8" });
res.end("404 Not Found");
return;
}
res.writeHead(500, { "Content-Type": "text/plain; charset=UTF-8" });
res.end("500 Internal Server Error");
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || "application/octet-stream";
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
});
}
const server = http.createServer((req, res) => {
const reqPath = (req.url || "/").split("?")[0];
const filePath = resolveFilePath(reqPath);
fs.stat(filePath, (err, stat) => {
if (!err && stat.isDirectory()) {
sendFile(path.join(filePath, "index.html"), res);
return;
}
sendFile(filePath, res);
});
});
server.listen(PORT, () => {
logger.info(`web running at http://localhost:${PORT}`);
});