forked from tomgco/gzippo
/
staticGzip.js
197 lines (166 loc) · 5.19 KB
/
staticGzip.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/*!
* Tom Gallacher
*
* MIT Licensed
*/
/**
* Module dependencies.
*/
var fs = require('fs'),
parse = require('url').parse,
path = require('path'),
mime = require('mime'),
zlib = require('zlib'),
staticSend;
try {
staticSend = require('connect').static.send;
} catch (e) {
staticSend = require('express').static.send;
}
/**
* Strip `Content-*` headers from `res`.
*
* @param {ServerResponse} res
* @api public
*/
var removeContentHeaders = function(res){
Object.keys(res._headers).forEach(function(field){
if (0 === field.indexOf('content')) {
res.removeHeader(field);
}
});
};
/**
* gzipped cache.
*/
var gzippoCache = {};
/**
* gzip file.
*/
var gzippo = function(filename, charset, callback) {
fs.readFile(filename, function (err, data) {
if (err) throw err;
zlib.gzip(data, function(err, result) {
callback(result);
});
});
};
/**
* By default gzip's static's that match the given regular expression /text|javascript|json/
* and then serves them with Connects static provider, denoted by the given `dirPath`.
*
* Options:
*
* - `maxAge` cache-control max-age directive, defaulting to 1 day
* - `clientMaxAge` client cache-control max-age directive, defaulting to 1 week
* - `contentTypeMatch` - A regular expression tested against the Content-Type header to determine whether the response
* should be gzipped or not. The default value is `/text|javascript|json/`.
* - `prefix` - A url prefix. If you want all your static content in a root path such as /resource/. Any url paths not matching will be ignored
*
* Examples:
*
* connect.createServer(
* connect.staticGzip(__dirname + '/public/');
* );
*
* connect.createServer(
* connect.staticGzip(__dirname + '/public/', {maxAge: 86400000});
* );
*
* @param {String} path
* @param {Object} options
* @return {Function}
* @api public
*/
exports = module.exports = function staticGzip(dirPath, options){
options = options || {};
var
maxAge = options.maxAge || 86400000,
contentTypeMatch = options.contentTypeMatch || /text|javascript|json/,
clientMaxAge = options.clientMaxAge || 604800000,
prefix = options.prefix || '';
if (!dirPath) throw new Error('You need to provide the directory to your static content.');
if (!contentTypeMatch.test) throw new Error('contentTypeMatch: must be a regular expression.');
return function staticGzip(req, res, next){
var url, filename, contentType, acceptEncoding, charset;
function pass(name) {
var o = Object.create(options);
o.path = name;
o.maxAge = maxAge;
staticSend(req, res, next, o);
}
function setHeaders(cacheObj) {
res.setHeader('Content-Type', contentType);
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Vary', 'Accept-Encoding');
res.setHeader('Content-Length', cacheObj.content.length);
res.setHeader('Last-Modified', cacheObj.mtime.toUTCString());
res.setHeader('Date', new Date().toUTCString());
res.setHeader('Expires', new Date(Date.now() + clientMaxAge).toUTCString());
res.setHeader('Cache-Control', 'public, max-age=' + (clientMaxAge / 1000));
res.setHeader('ETag', '"' + cacheObj.content.length + '-' + Number(cacheObj.mtime) + '"');
}
function sendGzipped(cacheObj) {
setHeaders(cacheObj);
res.end(cacheObj.content, 'binary');
}
function gzipAndSend(filename, gzipName, mtime) {
gzippo(filename, charset, function(gzippedData) {
gzippoCache[gzipName] = {
'ctime': Date.now(),
'mtime': mtime,
'content': gzippedData
};
sendGzipped(gzippoCache[gzipName]);
});
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next();
}
url = parse(req.url);
// Allow a url path prefix
if (url.pathname.substring(0, prefix.length) !== prefix) {
return next();
}
filename = path.join(dirPath, url.pathname.substring(prefix.length));
contentType = mime.lookup(filename);
charset = mime.charsets.lookup(contentType, 'UTF-8');
contentType = contentType + (charset ? '; charset=' + charset : '');
acceptEncoding = req.headers['accept-encoding'] || '';
//This is storing in memory for the moment, need to think what the best way to do this.
//Check file is not a directory
fs.stat(filename, function(err, stat) {
if (err || stat.isDirectory()) {
return pass(req.url);
}
if (!contentTypeMatch.test(contentType)) {
return pass(filename);
}
if (!~acceptEncoding.indexOf('gzip')) {
return pass(filename);
}
var base = path.basename(filename),
dir = path.dirname(filename),
gzipName = path.join(dir, base + '.gz');
if (req.headers['if-modified-since'] &&
gzippoCache[gzipName] &&
+stat.mtime <= new Date(req.headers['if-modified-since']).getTime()) {
setHeaders(gzippoCache[gzipName]);
removeContentHeaders(res);
res.statusCode = 304;
return res.end();
}
//TODO: check for pre-compressed file
if (typeof gzippoCache[gzipName] === 'undefined') {
gzipAndSend(filename, gzipName, stat.mtime);
} else {
if ((gzippoCache[gzipName].mtime < stat.mtime) ||
((gzippoCache[gzipName].ctime + maxAge) < Date.now())) {
gzipAndSend(filename, gzipName, stat.mtime);
} else {
sendGzipped(gzippoCache[gzipName]);
}
}
});
};
};