Write `file` to the response with a guessed content type. Returns false if it doesn't exist.
(res: ServerResponseLike, file: string)
| 83 | |
| 84 | /** Write `file` to the response with a guessed content type. Returns false if it doesn't exist. */ |
| 85 | async function serveFile(res: ServerResponseLike, file: string): Promise<boolean> { |
| 86 | try { |
| 87 | const content = await fs.readFile(file); |
| 88 | res.setHeader("Content-Type", MIME[path.extname(file).toLowerCase()] ?? "application/octet-stream"); |
| 89 | res.end(content); |
| 90 | return true; |
| 91 | } catch (err: unknown) { |
| 92 | if ((err as NodeJS.ErrnoException).code === "ENOENT") return false; |
| 93 | res.statusCode = 500; |
| 94 | res.end((err as NodeJS.ErrnoException).code ?? "read failed"); |
| 95 | return true; |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | // Minimal structural type so this helper isn't tied to the full http types. |
| 100 | type ServerResponseLike = { |