-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
70 lines (56 loc) · 1.96 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
const {spawn} = require('child_process');
// Pulled from `slang` lib to remove the dep
function dasherize(input) {
return input.replace(/\W+/g, '-')
.replace(/([a-z\d])([A-Z])/g, '$1-$2')
.toLowerCase();
}
function quote(val) {
// escape and quote the value if it is a string and this isn't windows
if (typeof val === 'string' && process.platform !== 'win32') {
val = '"' + val.replace(/(["\\$`])/g, '\\$1') + '"';
}
return val;
}
function weasyprint(input, options, callback) {
if (!options) {
options = {};
} else if (typeof options === 'function') {
callback = options;
options = {};
}
var output = options.output;
delete options.output;
var keys = Object.keys(options);
var args = [weasyprint.command];
keys.forEach(function (key, index, arry) {
arry[index] = key.length === 1 ? '-' + key : '--' + dasherize(key);
});
const isUrl = /^(https?|file):\/\//.test(input);
//if format is not specified and we are reading from stdin, than set default pdf format
if (!output && !('f' in options) && !('format' in options)) {
args.push('-f', 'pdf')
}
args.push(isUrl ? quote(input) : '-'); // stdin if HTML given directly
args.push(output ? quote(output) : '-'); // stdout if no output file
if (process.platform === 'win32') {
var child = spawn(args[0], args.slice(1));
} else {
// this nasty business prevents piping problems on linux
var child = spawn('/bin/sh', ['-c', args.join(' ') + ' | cat']);
}
// call the callback with null error when the process exits successfully
if (callback) {
child.on('exit', function () {
callback(null);
});
}
// write input to stdin if it isn't a url
if (!isUrl) {
child.stdin.end(input);
}
// return stdout stream so we can pipe
return child.stdout;
}
weasyprint.command = 'weasyprint';
module.exports = weasyprint;