diff --git a/lib/core/index.js b/lib/core/index.js index 920e55b9..8e062c90 100644 --- a/lib/core/index.js +++ b/lib/core/index.js @@ -111,6 +111,7 @@ module.exports = function createMiddleware(_dir, _options) { const headers = opts.headers; const weakEtags = opts.weakEtags; const handleOptionsMethod = opts.handleOptionsMethod; + const defaultType = opts.contentType || 'application/octet-stream'; opts.root = dir; if (defaultExt && /^\./.test(defaultExt)) { @@ -185,6 +186,7 @@ module.exports = function createMiddleware(_dir, _options) { let file = null; let gzippedFile = null; let brotliFile = null; + let contentType = null; try { decodeURIComponent(req.url); // check validity of url @@ -201,8 +203,11 @@ module.exports = function createMiddleware(_dir, _options) { ) ); // determine compressed forms if they were to exist - gzippedFile = `${file}.gz`; - brotliFile = `${file}.br`; + gzippedFile = file.endsWith('.gz') ? file : `${file}.gz`; + brotliFile = file.endsWith('.br') ? file : `${file}.br`; + + // Do MIME lookup, fall back to octet-stream + contentType = mime.lookup(file, defaultType); Object.keys(headers).forEach((key) => { res.setHeader(key, headers[key]); @@ -227,10 +232,6 @@ module.exports = function createMiddleware(_dir, _options) { function serve(stat) { - // Do a MIME lookup, fall back to octet-stream and handle gzip - // and brotli special case. - const defaultType = opts.contentType || 'application/octet-stream'; - let contentType = mime.lookup(file, defaultType); const range = (req.headers && req.headers.range); const lastModified = (new Date(stat.mtime)).toUTCString(); const etag = generateEtag(stat, weakEtags); @@ -252,12 +253,8 @@ module.exports = function createMiddleware(_dir, _options) { if (file === gzippedFile) { // is .gz picked up res.setHeader('Content-Encoding', 'gzip'); - // strip gz ending and lookup mime type - contentType = mime.lookup(path.basename(file, '.gz'), defaultType); } else if (file === brotliFile) { // is .br picked up res.setHeader('Content-Encoding', 'br'); - // strip br ending and lookup mime type - contentType = mime.lookup(path.basename(file, '.br'), defaultType); } if (typeof cacheControl === 'function') {