-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve-favicon.js
44 lines (34 loc) · 1.11 KB
/
serve-favicon.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
'use strict';
const etag = require('etag');
const fs = require('fs');
const DEFAULT_MAX_AGE = 60 * 60 * 24 * 365; // 1 year
function serveFavicon(app, options) {
const favicon = Buffer.isBuffer(options.favicon)
? options.favicon
: fs.readFileSync(options.favicon); // eslint-disable-line no-sync
const etagValue = etag(favicon);
const maxAge = typeof options.maxAge === 'number'
? options.maxAge
: DEFAULT_MAX_AGE;
const cacheControl = `public,max-age=${maxAge}`;
app.get('/favicon.ico', createHandler(favicon, etagValue, cacheControl));
}
function createHandler(favicon, etagValue, cacheControl) {
return function faviconHandler(req, res) {
res.set('cache-control', cacheControl);
res.set('etag', etagValue);
const {headers} = req;
if (
headers['if-none-match'] === etagValue &&
(headers['cache-control'] === undefined ||
headers['cache-control'].indexOf('no-cache') === -1)
) {
res.statusCode = 304;
res.send(null);
return;
}
res.set('content-type', 'image/x-icon');
res.send(favicon);
};
}
module.exports = serveFavicon;