forked from jonschlinkert/markdown-toc
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcli.js
executable file
·56 lines (48 loc) · 1.45 KB
/
cli.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
#!/usr/bin/env node
var fs = require('fs');
var toc = require('./index.js');
var utils = require('./lib/utils');
var args = utils.minimist(process.argv.slice(2), {
boolean: ['i', 'json']
});
if (args._.length !== 1) {
console.error([
'Usage: markdown-toc [--json] [-i] <input> ',
'',
' input: The markdown file to parse for table of contents,',
' or "-" to read from stdin.',
'',
' --json: Print the TOC in json format',
'',
' -i: Edit the <input> file directly, injecting the TOC at <!-- toc -->',
' (Without this flag, the default is to print the TOC to stdout.)'
].join('\n'));
process.exit(1);
}
if (args.i && args.json) {
console.error('markdown-toc: you cannot use both --json and -i');
process.exit(1);
}
if (args.i && args._[0] === '-') {
console.error('markdown-toc: you cannot use -i with "-" (stdin) for input');
process.exit(1);
}
var input = process.stdin;
if (args._[0] !== '-') input = fs.createReadStream(args._[0]);
input.pipe(utils.concat(function (input) {
if (args.i) {
var newMarkdown = toc.insert(input.toString());
fs.writeFileSync(args._[0], newMarkdown);
} else {
var parsed = toc(input.toString());
output(parsed);
}
}))
input.on('error', function onErr(err) {
console.error(err);
process.exit(1);
})
function output(parsed) {
if (args.json) return console.log(JSON.stringify(parsed.json, null, ' '));
process.stdout.write(parsed.content);
}