UNPKG

als-send-file

Version:

file serving with advanced options for caching, headers, and error handling, compatible with Express middleware.

19 lines (18 loc) 869 B
const fileHandler = require('./file-handler') const optionsSchema = require('./options-schema') const { isFunction, string } = require('als-schema') const { join } = require('path') function sendFileMw(root, httpErrorHandler, $options = {}) { root = string(3,255,join(__dirname,'..','..','..'))(root) httpErrorHandler = isFunction((res, code, msg) => { res.writeHead(code); res.end(msg); })(httpErrorHandler) const defaultOptions = optionsSchema.validate($options) return (req, res, next) => { res.sendFile = (filePath, options = defaultOptions, httpErrHandler = httpErrorHandler) => { options = optionsSchema.validate({ ...defaultOptions, ...options }) filePath = join(root, filePath) return fileHandler(req, res, filePath, options, httpErrHandler) } next() } } module.exports = sendFileMw