UNPKG

kequapp

Version:

DEPRECATED: renamed to @kequtech/arbor

43 lines (42 loc) 1.24 kB
import fs from 'node:fs'; import path from 'node:path'; import { Ex } from "../ex.js"; import { guessContentType } from "../utils/guess-content-type.js"; export async function sendFile(req, res, location, contentType) { const asset = path.join(process.cwd(), location); const stats = await getStats(asset); res.setHeader('Content-Type', contentType ?? guessContentType(location)); res.setHeader('Content-Length', stats.size); if (req.method === 'HEAD') { res.end(); return; } try { await new Promise((resolve, reject) => { const stream = fs.createReadStream(asset); stream.pipe(res); stream.on('end', resolve); stream.on('error', reject); res.on('close', () => { stream.destroy(); }); }); } catch (error) { throw Ex.InternalServerError(undefined, { location: asset, error, }); } } async function getStats(location) { try { const stats = await fs.promises.stat(location); if (stats.isFile()) return stats; } catch (_error) { // fail } throw Ex.NotFound(undefined, { location }); }