(req: Request, res: Response)
| 54 | * @param res Response |
| 55 | */ |
| 56 | export const sendFile = <Request extends Req = Req, Response extends Res = Res>(req: Request, res: Response) => ( |
| 57 | path: string, |
| 58 | opts: SendFileOptions = {}, |
| 59 | cb?: (err?: any) => void |
| 60 | ) => { |
| 61 | const { root, headers = {}, encoding = 'utf-8', caching, ...options } = opts |
| 62 | |
| 63 | if (!isAbsolute(path) && !root) throw new TypeError('path must be absolute') |
| 64 | |
| 65 | if (caching) enableCaching(res, caching) |
| 66 | |
| 67 | const filePath = root ? join(root, path) : path |
| 68 | |
| 69 | const stats = statSync(filePath) |
| 70 | |
| 71 | headers['Content-Encoding'] = encoding |
| 72 | |
| 73 | headers['Last-Modified'] = stats.mtime.toUTCString() |
| 74 | |
| 75 | headers['Content-Type'] = contentType(extname(path)) |
| 76 | |
| 77 | headers['ETag'] = createETag(stats, encoding) |
| 78 | |
| 79 | let status = 200 |
| 80 | |
| 81 | if (req.headers['range']) { |
| 82 | status = 206 |
| 83 | const [x, y] = req.headers.range.replace('bytes=', '').split('-') |
| 84 | const end = (options.end = parseInt(y, 10) || stats.size - 1) |
| 85 | const start = (options.start = parseInt(x, 10) || 0) |
| 86 | |
| 87 | if (start >= stats.size || end >= stats.size) { |
| 88 | res |
| 89 | .writeHead(416, { |
| 90 | 'Content-Range': `bytes */${stats.size}` |
| 91 | }) |
| 92 | .end() |
| 93 | return res |
| 94 | } |
| 95 | headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}` |
| 96 | headers['Content-Length'] = end - start + 1 |
| 97 | headers['Accept-Ranges'] = 'bytes' |
| 98 | } else { |
| 99 | headers['Content-Length'] = stats.size |
| 100 | } |
| 101 | |
| 102 | for (const [k, v] of Object.entries(headers)) res.setHeader(k, v) |
| 103 | |
| 104 | res.writeHead(status, headers) |
| 105 | |
| 106 | const stream = createReadStream(filePath, options) |
| 107 | |
| 108 | if (cb) stream.on('error', (err) => cb(err)).on('end', () => cb()) |
| 109 | |
| 110 | stream.pipe(res) |
| 111 | |
| 112 | return res |
| 113 | } |
no test coverage detected