-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (75 loc) · 1.75 KB
/
index.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
/*
* dependencies
*/
var crypto = require('crypto');
var fs = require('fs');
var DEFAULT = __dirname + '/favicon.ico';
/**
* Bounce favicon requests.
*
* @param {String} path
* @param {Object} options
* @api public
*
*/
module.exports = function (path, options) {
var options = options || {}
, path = path || DEFAULT
, maxAge = options.maxAge || 86400000
, icon; // favicon cache
return function *favicon(next){
if ('/favicon.ico' == this.path) {
if (icon) {
this.set(icon.headers);
this.body = icon.body;
} else {
try{
var buf = yield readFile(path);
}catch(e){
var buf = yield readFile(DEFAULT);
}
icon = {
headers: {
'Content-Type': 'image/x-icon'
, 'Content-Length': buf.length
, 'ETag': '"' + md5(buf) + '"'
, 'Cache-Control': 'public, max-age=' + (maxAge / 1000)
},
body: buf
};
this.set(icon.headers);
this.body = icon.body;
}
}else{
// if not favicon.ico request yield downstream middleware
yield next;
}
};
};
/**
* thunk like readFile
*
* @param {String} file
* @return {Function}
* @api private
*
*/
function readFile (file) {
return function (fn) {
return fs.readFile(file, fn);
}
}
/**
* md5 helper
*
* @param {String} str
* @param {String} encoding (optional)
* @api private
*
*/
function md5(str, encoding){
return crypto
.createHash('md5')
.update(str, 'utf8')
.digest(encoding || 'hex');
};