@tdb/web
Version:
Common condiguration for serving a web-site and testing web-based UI components.
22 lines (18 loc) • 603 B
text/typescript
import { Request, Response, NextFunction } from 'express';
import { parse as parseUrl } from 'url';
import { fsPath } from './common';
export function fileHandler(urlPath: string, filePath: string) {
filePath = fsPath.resolve(filePath);
return (req: Request, res: Response, next: NextFunction) => {
// Only allow GET requests.
if (req.method !== 'GET') {
return next();
}
// Match the URL.
const requestUrl = parseUrl(req.url, true);
if (requestUrl.href !== urlPath && requestUrl.pathname !== urlPath) {
return next();
}
res.sendFile(filePath);
};
}