This repository has been archived by the owner on Mar 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform-image-middleware.js
68 lines (49 loc) · 1.61 KB
/
transform-image-middleware.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
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
const mimeTypes = {
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.png': 'image/png',
'.webp': 'image/webp'
};
let rootImages;
const transformImage = (req, res, next) => {
let matches = req.url.match(/^(.*?(?:jpg|jpeg|png)).*?nf_resize=(fit|smartcrop)/);
if (matches) {
let filename = path.join(rootImages, decodeURI(matches[1]));
fs.access(filename, fs.constants.R_OK, (err) => {
if (err) {
console.error(err);
return;
}
});
res.setHeader('Expires', new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toUTCString());
res.setHeader('Cache-control', 'max-age=31536000, public');
res.setHeader('Last-Modified', new Date().toUTCString());
if (req.headers['if-modified-since']) {
res.statusCode = 304;
res.setHeader('Last-Modified', req.headers['if-modified-since']);
return;
} else {
let options = {
fit: sharp.fit.cover,
position: sharp.strategy.entropy
};
options.width = (matches = req.url.match(/(?:\?|&)w=(\d*)/)) ? parseInt(matches[1]) : null;
options.height = (matches = req.url.match(/(?:\?|&)h=(\d*)/)) ? parseInt(matches[1]) : null;
res.setHeader('content-type', mimeTypes[path.extname(filename)]);
fs.createReadStream(filename)
.on('error', (err) => {
console.error(err);
return;
})
.pipe(sharp().resize(options))
.pipe(res);
}
} else next();
};
module.exports = (root) => {
rootImages = root;
return transformImage;
};