-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpdc.js
81 lines (65 loc) · 1.65 KB
/
pdc.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
var spawn = require('child_process').spawn;
module.exports = pdc;
// pdcStream(from, to, [args,] [opts])
function pdcStream(from, to, args, opts) {
var defaultArgs = [ '-f', from, '-t', to ];
// sanitize arguments
// no args, no opts
if (arguments.length == 2) {
args = defaultArgs;
} else {
// concatenate arguments
args = defaultArgs.concat(args);
}
// start pandoc (with or without options)
var pandoc;
if (typeof opts == 'undefined')
pandoc = spawn(pdc.path, args);
else
pandoc = spawn(pdc.path, args, opts);
return pandoc;
}
// pdc(src, from, to, [args,] [opts,] cb)
function pdc(src, from, to, args, opts, cb) {
var pandoc;
if (arguments.length == 4) {
cb = args;
pandoc = pdcStream(from, to);
} else if (arguments.length == 5) {
cb = opts;
pandoc = pdcStream(from, to, args);
} else {
pandoc = pdcStream(from, to, args, opts);
}
var result = '';
var error = '';
// listen on error
pandoc.on('error', function (err) {
return cb(err);
});
// collect result data
pandoc.stdout.on('data', function (data) {
result += data;
});
// collect error data
pandoc.stderr.on('data', function (data) {
error += data;
});
// listen on exit
pandoc.on('close', function (code) {
var msg = '';
if (code !== 0)
msg += 'pandoc exited with code ' + code + (error ? ': ' : '.');
if (error)
msg += error;
if (msg)
return cb(new Error(msg));
cb(null, result);
});
// finally, send source string
pandoc.stdin.end(src, 'utf8');
}
// export stream version
pdc.stream = pdcStream;
// name of or path to pandoc executable
pdc.path = 'pandoc';