UNPKG

express-cache-file

Version:

Express middleware to cache static files in server memory

48 lines (47 loc) 1.76 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.cacheFile = void 0; const cache_1 = __importDefault(require("./cache")); const path_1 = require("path"); const fs_1 = __importDefault(require("./fs")); const size_1 = __importDefault(require("./size")); function cacheFile(root, options = {}) { var _a; const redirect = (_a = options.redirect) !== null && _a !== void 0 ? _a : true; const cache = { capacity: (0, size_1.default)(options.cacheSize), usedSize: 0, files: {}, }; let readFile = (0, fs_1.default)(options.readMode); readFile = (0, cache_1.default)(readFile, cache, options.update || {}); return function (req, res, next) { const file = (0, path_1.join)(root, req.path); readFile(file, (err, content) => { if (redirect && err && err.code === 'EISDIR') { const indexFile = (0, path_1.join)(file, 'index.html'); readFile(indexFile, (err, content) => sendResponse(req, res, next, err, content)); return; } return sendResponse(req, res, next, err, content); }); }; } exports.cacheFile = cacheFile; function sendResponse(req, res, next, err, content) { if (!err) return sendContent(res, content); if (err.code === 'ENOENT' || err.code === 'EISDIR') next(); else next(`Cannot ${req.method} ${req.originalUrl}`); } function sendContent(res, content) { res.setHeader('Content-Type', content.mimeType); res.write(content.buffer); res.end(); } exports.default = cacheFile;