mdview 1.59 KB
#!/usr/bin/env node

"use strict";
const PKG = require('../package.json'),
    program = require('commander'),
    chalk = require('chalk'),
    path = require('path'),
    fs = require('fs-extra');

program
    .version(PKG.version);

program
    .command('export <markdown_file> [html_file]')
    .alias('e')
    .description('export markdown to html')
    .option('-A --abstract', 'abstract to current path')
    .action(function (md, html, options) {
        //判断目标输出参数
        if (!fs.existsSync(md)) {
            console.error(chalk.red(md + ' is not found'));
            return
        }
        let relative_path = '';
        let abstract = options.abstract;
        let default_name = path.parse(md).name + '.html';
        if (!html) {
            html = md.replace(/\.md$/g, '') + '.html'
        }
        let target = path.parse(html);
        if (!target.ext) { //目标没有后缀作为目录,添加md的同名html
            html = path.join(html, default_name)
        }
        let output = path.resolve(process.cwd(), html);
        fs.ensureFileSync(output);
        if (!abstract) {
            // 默认使用相对的资源路径
            relative_path = path.relative(path.dirname(output), 'themes');
        }
        const viewer = new (require('../lib/view-markdown'))(process.cwd(), {relative_path: relative_path});
        let result = viewer.render(md, 'metro-lake');

        fs.writeFile(output, result);
        console.log('html is exported to', chalk.green(output))
    });

program
    .parse(process.argv);

if (process.argv.length === 2) {
    program.outputHelp();
}