-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserve.js
43 lines (43 loc) · 1.8 KB
/
serve.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var mime = require('mime'),
fs = require('fs');
/**
* Express middleware that serves static gzipped assets if they are available with specified max-age
* @param {String} assetPath where the assets are stored
* @param {String} cacheControl time in seconds the asset is to be cached ex: 'public, max-age=512000'
* @param {RegExp} exclusion regex used to match filepaths to exclude
* @param {Boolean} printError boolean whether to print the error for gzip
* @return {function}
*/
module.exports = function(assetPath,cacheControl,exclusion,printError) {
/**
* Executed when called by express
* @param {Object} req request from express
* @param {Object} res response from express
* @param {Function} next next in express
*/
return function(req, res, next) {
var acceptEncodingsString = req.get('Accept-Encoding'),
originalPath = req.path;
res.setHeader('Cache-Control', cacheControl);
if(originalPath.includes('.') && !exclusion.test(originalPath) && typeof acceptEncodingsString != 'undefined') {
var acceptEncodings = acceptEncodingsString.split(", ");
try {
var stats = fs.statSync(`${assetPath}${originalPath}.gz`);
if(acceptEncodings.indexOf('gzip') >= 0 && stats.isFile()) {
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Vary', 'Accept-Encoding');
req.url = `${req.url}.gz`;
var type = mime.lookup(`${assetPath}${originalPath}`);
if (typeof type != 'undefined') {
var charset = mime.charsets.lookup(type);
res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
}
}
} catch(e) {
if(printError)
console.log(`GZIP - ERROR - ${assetPath}${originalPath}.gz`);
}
}
next();
}
};