UNPKG

als-send-file

Version:

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

33 lines (29 loc) 1.5 kB
const { stat } = require('fs/promises') const { basename } = require('path') const mime = require('mime-types'); const generateETag = require('./etag') const sendFile = require('./send-file') const cachControl = require('./cache-control') const optionsSchema = require('./options-schema') /** * Handles file requests and sends the file to the client. * @param {http.IncomingMessage} req - The request object. * @param {http.ServerResponse} res - The response object. * @param {string} filePath - The path to the file. * @param {Object} options - Options for handling the file. * @param {Function} httpErrorHandler - Function to handle HTTP errors. */ async function fileHandler(req, res, filePath, options, httpErrorHandler) { let stats const name = basename(filePath) try { stats = await stat(filePath) } catch (error) { return httpErrorHandler(res, 404, `File ${name} not found`) } const { download, charset, etag, maxAge, noCache, noStore, public } = optionsSchema.validate(options) if (etag && generateETag(req, res, stats)) return cachControl(res, { maxAge, noCache, noStore, public }) res.setHeader('Content-Disposition', `${download ? 'attachment' : 'inline'}; filename="${name}"`) const contentType = mime.lookup(name) || 'text/plain'; res.setHeader('Content-Type', `${contentType}${charset ? `; charset=${charset}` : ''}`); return sendFile(req, res, filePath, stats, httpErrorHandler) } module.exports = fileHandler