-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
105 lines (85 loc) · 2.55 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
var basename = require('path').basename;
var dirname = require('path').dirname;
var extname = require('path').extname;
var debug = require('debug')('metalsmith-pandoc');
var pdc = require('pdc');
var match = require('multimatch');
var async = require('async');
var which = require('which');
var install = require('system-install')();
// check if pandoc is installed
try {
pdc.path = which.sync('pandoc');
} catch (e) {
var err = 'metalsmith-pandoc: ERROR, pandoc not found. ';
err += 'Install pandoc on your system with `' + install + ' pandoc`.';
// fail hard
throw new Error(err)
}
/**
* Expose `plugin`.
*/
module.exports = plugin;
/**
* Metalsmith plugin to convert files using pandoc.
*
*/
function plugin(options){
options = options || {};
var from = options.from || 'markdown';
var to = options.to || 'html5';
var args = options.args || [];
var opts = options.opts || {};
var pattern = options.pattern || '**/*.md';
var extension = options.ext || '.html';
if (to === 'docx' || to === 'pdf') {
opts.encoding = 'binary'
}
return function(files, metalsmith, done){
selectedFiles = match(Object.keys(files), pattern)
async.eachLimit(selectedFiles, 100, function(file, cb){
var data = files[file];
var dir = dirname(file);
var html = basename(file, extname(file)) + extension;
if ('.' != dir) html = dir + '/' + html;
debug('Converting file %s', file);
var md = data.contents.toString();
pandoc = pdc.stream(from, to, args, opts);
var result = Buffer.alloc(0);
var chunks = [];
var size = 0;
var error = '';
// listen on error
pandoc.on('error', function (err) {
debug('error: ', err);
return cb(err);
});
// collect result data
pandoc.stdout.on('data', function (data) {
chunks.push(data);
size += data.length;
});
// 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));
var result = Buffer.concat(chunks, size);
data.contents = result;
delete files[file];
files[html] = data;
cb(null, result);
});
// finally, send source string
pandoc.stdin.end(md, 'utf8');
}, done);
};
}