|
| 1 | +import { createReadStream } from "node:fs"; |
| 2 | +import { stat } from "node:fs/promises"; |
| 3 | +import { createServer } from "node:http"; |
| 4 | +import { dirname, extname, join, normalize, sep } from "node:path"; |
| 5 | +import { fileURLToPath } from "node:url"; |
| 6 | + |
| 7 | +const projectRoot = dirname(dirname(fileURLToPath(import.meta.url))); |
| 8 | +const requestedDir = process.argv[2] ?? "src"; |
| 9 | +const rootDir = join(projectRoot, requestedDir); |
| 10 | +const port = Number(process.env.PORT ?? 3001); |
| 11 | + |
| 12 | +const mimeTypes = { |
| 13 | + ".css": "text/css; charset=utf-8", |
| 14 | + ".html": "text/html; charset=utf-8", |
| 15 | + ".ico": "image/x-icon", |
| 16 | + ".jpg": "image/jpeg", |
| 17 | + ".js": "text/javascript; charset=utf-8", |
| 18 | + ".png": "image/png", |
| 19 | +}; |
| 20 | + |
| 21 | +function getFilePath(url) { |
| 22 | + const pathname = decodeURIComponent( |
| 23 | + new URL(url, `http://localhost`).pathname |
| 24 | + ); |
| 25 | + const relativePath = pathname === "/" ? "index.html" : pathname.slice(1); |
| 26 | + const filePath = normalize(join(rootDir, relativePath)); |
| 27 | + |
| 28 | + if (!filePath.startsWith(`${rootDir}${sep}`) && filePath !== rootDir) { |
| 29 | + return null; |
| 30 | + } |
| 31 | + |
| 32 | + return filePath; |
| 33 | +} |
| 34 | + |
| 35 | +const server = createServer(async (request, response) => { |
| 36 | + const filePath = getFilePath(request.url ?? "/"); |
| 37 | + |
| 38 | + if (!filePath) { |
| 39 | + response.writeHead(400); |
| 40 | + response.end("Bad request"); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + try { |
| 45 | + const fileStat = await stat(filePath); |
| 46 | + |
| 47 | + if (!fileStat.isFile()) { |
| 48 | + response.writeHead(404); |
| 49 | + response.end("Not found"); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + response.writeHead(200, { |
| 54 | + "Content-Length": fileStat.size, |
| 55 | + "Content-Type": |
| 56 | + mimeTypes[extname(filePath)] ?? "application/octet-stream", |
| 57 | + }); |
| 58 | + createReadStream(filePath).pipe(response); |
| 59 | + } catch { |
| 60 | + response.writeHead(404); |
| 61 | + response.end("Not found"); |
| 62 | + } |
| 63 | +}); |
| 64 | + |
| 65 | +server.listen(port, "127.0.0.1", () => { |
| 66 | + console.log(`Serving ${requestedDir}/ at http://127.0.0.1:${port}`); |
| 67 | +}); |
0 commit comments