-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexpressThumbnail.js
70 lines (54 loc) · 1.85 KB
/
expressThumbnail.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
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var lwip = require('lwip');
function convert(location, filepath, width, height, cb) {
mkdirp(path.dirname(location), function(err) {
if (err) { return cb(err); }
lwip.open(filepath, function(err, image) {
if (err) { return cb(err); }
var widthRatio = width / image.width();
var heightRatio = height / image.height();
var ratio = Math.max(widthRatio, heightRatio);
image
.batch()
.scale(ratio)
.crop(width, height)
.writeFile(location, function (err) {
return cb(err);
});
});
});
}
function register(rootDir, options) {
rootDir = path.normalize(rootDir);
options = options || {};
options.cacheDir = options.cacheDir || path.join(rootDir, '.thumb'); // cache folder, default to [root dir]/.thumb
return function (req, res, next) {
var filename = path.normalize(decodeURI(req.url.replace(/\?(.*)/, '')));
var filepath = path.join(rootDir, filename);
var dimension = req.query.thumb || '';
var dimensions = dimension.split('x');
var location = path.join(options.cacheDir, dimension, filename);
fs.stat(filepath, function (err, stats) {
// go forward
if (err || !stats.isFile()) { return next(); }
// send original file
if (!dimension) { return res.sendFile(filepath); }
// send converted file
fs.exists(location, function (exists) {
// file was found in cache
if (exists) { return res.sendFile(location); }
// convert and send
convert(location, filepath, +dimensions[0], +dimensions[1], function (err) {
if (err) {
console.log(err);
return next();
}
return res.sendFile(location);
});
});
});
};
}
exports.register = register;