kequapp
Version:
A minimal, zero-magic Node web framework built on native APIs
43 lines (42 loc) • 1.24 kB
JavaScript
import fs from 'node:fs';
import path from 'node:path';
import guessContentType from "../../util/guess-content-type.js";
import Ex from "../tools/ex.js";
export default 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 });
}