mdview 1.39 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('-T --theme [theme_name]', 'css theme for html')
    .action(function (md, html, options) {
        //判断目标输出参数
        if (!fs.existsSync(md)) {
            console.error(chalk.red(md + ' is not found'));
            return
        }
        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);

        const viewer = new (require('../lib/view-markdown'))(process.cwd(), {inline: true});
        let theme = options.theme || 'news';
        let result = viewer.render(md, theme);

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

program
    .parse(process.argv);

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