-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (73 loc) · 1.99 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
69
70
71
72
73
74
75
76
77
78
79
80
81
const path = require('path');
const fs = require('fs');
const express = require('express');
const gm = require('gm').subClass({imageMagick: true});
const mkdirp = require('mkdirp');
const app = express();
const dir = process.env.BIN || path.join(__dirname, 'bin');
const cache = process.env.CACHE || path.join(__dirname, 'cache');
const pass = process.env.FORCE_PASS || undefined;
const maxAge = process.env.MAX_AGE || undefined;
app.get('/*', (req, res, next)=> {
let size = req.query.image_width;
let force = req.query.hasOwnProperty('force') && req.query.force == pass;
if (!size || !isValidSize(size)) {
return next();
}
let xpath = decodeURI(req.path);
let filePath = path.join(dir, xpath);
let cachedPath = path.join(cache, path.join(
path.dirname(xpath),
size + "_" + path.basename(xpath)));
fs.access(filePath, fs.constants.R_OK, (err)=> {
if (err) {
next();
return;
}
if (force) {
doit();
} else {
fs.access(cachedPath, fs.constants.R_OK, (err) => {
if (err) return doit();
res.sendFile(cachedPath);
});
}
});
function doit() {
mkdirp(path.dirname(cachedPath), (err)=> {
if (err) {
console.error(err);
next();
return;
}
gm(filePath)
.resize(size)
.stream(function (err, stdout, stderr) {
if (err) {
console.error(err);
next();
return;
}
var writeStream = fs.createWriteStream(cachedPath);
writeStream.on("error", console.error);
stdout.pipe(writeStream);
stdout.pipe(res);
stderr.pipe(process.stderr);
});
});
}
});
// Allow sizes in power of 2 up to 4k
function isValidSize(size) {
return !(size & (size - 1)) && size <= 4096;
}
app.use(function (err, req, res, next) {
console.error(err.stack);
next();
});
const opts = {};
if (maxAge) {
opts.maxage = maxAge;
}
app.use(express.static(dir, opts));
app.listen(process.env.PORT || 8080);