Update project files
This commit is contained in:
46
server.mjs
Normal file
46
server.mjs
Normal file
@@ -0,0 +1,46 @@
|
||||
import { createServer } from "node:http";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { extname, resolve, sep } from "node:path";
|
||||
|
||||
const root = resolve(process.cwd());
|
||||
const port = Number(process.env.PORT || 4173);
|
||||
const host = process.env.HOST || "127.0.0.1";
|
||||
|
||||
const mimeTypes = new Map([
|
||||
[".html", "text/html; charset=utf-8"],
|
||||
[".css", "text/css; charset=utf-8"],
|
||||
[".js", "text/javascript; charset=utf-8"],
|
||||
[".json", "application/json; charset=utf-8"],
|
||||
[".png", "image/png"],
|
||||
[".jpg", "image/jpeg"],
|
||||
[".jpeg", "image/jpeg"],
|
||||
[".webp", "image/webp"],
|
||||
[".svg", "image/svg+xml"],
|
||||
]);
|
||||
|
||||
const server = createServer(async (request, response) => {
|
||||
try {
|
||||
const requestUrl = new URL(request.url, `http://${host}`);
|
||||
const pathname = requestUrl.pathname === "/" ? "/index.html" : decodeURIComponent(requestUrl.pathname);
|
||||
const filePath = resolve(root, `.${pathname.replaceAll("/", sep)}`);
|
||||
|
||||
if (filePath !== root && !filePath.startsWith(`${root}${sep}`)) {
|
||||
response.writeHead(403);
|
||||
response.end("Forbidden");
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await readFile(filePath);
|
||||
response.writeHead(200, {
|
||||
"content-type": mimeTypes.get(extname(filePath)) || "application/octet-stream",
|
||||
});
|
||||
response.end(data);
|
||||
} catch {
|
||||
response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
|
||||
response.end("Not found");
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(port, host, () => {
|
||||
console.log(`Portfolio preview running at http://${host}:${port}/`);
|
||||
});
|
||||
Reference in New Issue
Block a user