forked from sindresorhus/pageres
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
86 lines (66 loc) · 1.91 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
82
83
84
85
86
'use strict';
var spawn = require('child_process').spawn;
var path = require('path');
var urlMod = require('url');
var slugifyUrl = require('slugify-url');
var phantomjsBin = require('phantomjs').path;
var base64 = require('base64-stream');
var assign = require('object-assign');
function runPhantomjs(options) {
var cp = spawn(phantomjsBin, [
path.join(__dirname, 'converter.js'),
JSON.stringify(options)
]);
var stream = cp.stdout.pipe(base64.decode());
process.stderr.setMaxListeners(0);
cp.stdout.on('data', function (data) {
// stupid phantomjs outputs this on stdout...
if (/Couldn\'t load url/.test(data)) {
return stream.emit('error', new Error('Couldn\'t load url'));
}
});
cp.stderr.on('data', function (data) {
// ignore phantomjs noise
if (/ phantomjs\[/.test(data)) {
return;
}
stream.emit('error', data);
});
return stream;
}
function generateSizes(url, size, opts) {
url = url.replace(/^localhost/, 'http://$&');
url = urlMod.parse(url).protocol ? url : 'http://' + url;
// strip `www.`
url = url.replace(/^(?:https?:\/\/)?www\./, '');
// make it a valid filename
// remove | ? : * " < > \ characters that are not
// removed by slugify-url and are invalid file names
var filenameUrl = slugifyUrl(url).replace(/\||\?|\:|\*|\"|\<|\>|\\/g, '');
var filename = filenameUrl + '-' + size + '.png';
var dim = size.split(/x/i);
var stream = runPhantomjs([{}, opts, {
url: url,
width: dim[0],
height: dim[0]
}].reduce(assign));
stream.filename = filename;
return stream;
}
module.exports = function (urls, sizes, opts, cb) {
opts = opts || {};
cb = cb || function () {};
if (urls.length === 0) {
return cb(new Error('URLs required'));
}
if (sizes.length === 0) {
return cb(new Error('Sizes required'));
}
var items = [];
urls.forEach(function (url) {
sizes.forEach(function (size) {
items.push(generateSizes(url, size, opts));
});
});
cb(null, items);
};