forked from franksoftgrid/express-resize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (47 loc) · 1.37 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
'use strict';
///////////////
///INCLUDES///
//////////////
var sharp = require('sharp');
var pathUtil = require('path');
var util = require('./utils/utils');
///////////////
//PUBLIC API//
//////////////
module.exports = resizer;
///////////////
/////MAIN/////
//////////////
function resizer(req, res, next) {
var path = decodeURI(util.relativePath(req._parsedUrl.pathname));
var requestedAsset = util.parseReqURL(path);
if (requestedAsset.constructor === Array) {
requestedAsset = requestedAsset.join('/');
}
var ext = pathUtil.extname(requestedAsset).toLowerCase();
var formats = ['.jpg', '.jpeg', '.gif', '.png', '.svg'];
if (formats.indexOf(ext) !== -1) {
util.assetAvailable(path, function (err) {
if (err) {
return res.sendStatus(404);
}
var reqParams = util.params(req);
if (reqParams !== null && (reqParams.hasOwnProperty('height') || reqParams.hasOwnProperty('width'))) {
if (ext == '.gif') {
// pass through gifs - sharp doesn't support gif output
return res.sendFile(process.cwd() + '/' + path);
} else {
res.writeHead(200, {'Content-Type': 'image/' + ext.slice(1)});
return sharp(path)
.resize(reqParams.width, reqParams.height)
.progressive()
.pipe(res);
}
}
return res.sendFile(process.cwd() + '/' + path);
})
}
else {
return next();
}
}