cli.js 1.4 KB
Newer Older
Lab机器人's avatar
readme  
Lab机器人 已提交
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
#!/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> \n\
\n\
  input:  The markdown file to parse for table of contents,\n\
          or "-" to read from stdin.\n\
\n\
  --json: Print the TOC in json format\n\
\n\
  -i:     Edit the <input> file directly, adding the TOC at <!-- toc -->\n\
          (The default is to print the TOC to stdout.)\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);
}