(
res: ServerResponse,
absolutePath: string,
options: { rootDir: string; method: string; extraHeaders?: Record<string, string> }
)
| 65 | * asked us to skip, which keeps it read-only by construction. |
| 66 | */ |
| 67 | export function sendFile( |
| 68 | res: ServerResponse, |
| 69 | absolutePath: string, |
| 70 | options: { rootDir: string; method: string; extraHeaders?: Record<string, string> } |
| 71 | ): void { |
| 72 | let stats: fs.Stats; |
| 73 | try { |
| 74 | stats = fs.statSync(absolutePath); |
| 75 | } catch { |
| 76 | sendText(res, 404, 'Not found', options.method); |
| 77 | return; |
| 78 | } |
| 79 | |
| 80 | const relative = path.relative(options.rootDir, absolutePath); |
| 81 | res.writeHead(200, { |
| 82 | 'Content-Type': contentTypeFor(absolutePath), |
| 83 | 'Content-Length': String(stats.size), |
| 84 | 'Cache-Control': cacheControlFor(relative), |
| 85 | 'Last-Modified': stats.mtime.toUTCString(), |
| 86 | ...options.extraHeaders, |
| 87 | }); |
| 88 | |
| 89 | if (options.method === 'HEAD') { |
| 90 | res.end(); |
| 91 | return; |
| 92 | } |
| 93 | |
| 94 | const stream = fs.createReadStream(absolutePath); |
| 95 | stream.on('error', () => { |
| 96 | // Headers are already out, so there is no status left to change: drop the |
| 97 | // connection so the client sees a truncated body rather than a silent lie. |
| 98 | res.destroy(); |
| 99 | }); |
| 100 | res.on('close', () => stream.destroy()); |
| 101 | stream.pipe(res); |
| 102 | } |
| 103 | |
| 104 | /** Send a plain-text status response (the error path for a browser or curl). */ |
| 105 | export function sendText(res: ServerResponse, status: number, message: string, method: string): void { |
no test coverage detected