Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serve compressed files if already exist #852

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 7 additions & 10 deletions lib/core/index.js
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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
Expand All @@ -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]);
Expand All @@ -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);
Expand All @@ -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') {
Expand Down