-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (53 loc) · 1.41 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
/**
* Module dependencies.
*/
var path = require('path');
var merge = require('utils-merge');
var parseurl = require('parseurl');
var mime = require('mime');
var gm = require('gm');
/**
* @param {String} root
* @param {Object} options
* @return {Function}
* @api public
*/
exports = module.exports = function serveStatic(root, options) {
if (!root) {
throw new TypeError('root path required')
}
if (typeof root !== 'string') {
throw new TypeError('root path must be a string')
}
// copy options object
options = merge({}, options)
// resolve root to absolute
root = path.resolve(root)
// setup options for send
options.root = root;
options.extensions = options.extensions
? options.extensions
: ['jpg', 'png'];
return function expressImage(req, res, next) {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next()
}
var pathname = path.join(options.root, parseurl(req).pathname);
var extension = path.extname(pathname).substr(1);
var params = req.query;
if (options.extensions.indexOf(extension) === -1) {
return next();
}
res.set('content-type', mime.lookup(extension))
var width = params.w;
var height = params.h;
var flag = '' + (params.f ? '!' : '');
if (!(width || height)) {
res.sendFile(pathname);
}
gm(pathname)
.resize(width, height, flag)
.stream()
.pipe(res);
}
}