Skip to content
Go back

Commander常见用法

Published:  at  06:24 PM
#!/usr/bin/env node

const commander = require('commander')
const program = new commander.Command()
const pkg = require('../package.json')

program
    .name(Object.keys(pkg.bin)[0])
    .usage('<cmd> [option]')
    .version(pkg.version)
    .option('-d, --debug', 'start debug mode', false)
    .option('-e --envName <envName>', 'fetch the environment', 'development')

const clone = program.command('clone <source> [destination]');
clone
    .description('clone an existing project')
    .option('-f, --force', 'clone force')
    .action((source, dest, cmdObj) => {
        console.log('clone', source, dest, cmdObj.force);
    })

const server = new commander.Command('server')
server.command('start [port]')
    .description('start server at specified port')
    .action((port) => {
        console.log(`start server at ${port} ...`);
    })

server.command('stop')
    .description("stop server")
    .action(() => {
        console.log("stop server");
    })

program.command('install [name] [path]', 'install package at specified path', {
    executableFile: 'npm',  // 当前install命令执行,相当于yarn add执行
    // isDefault: true,        // 这里设置为true,当执行脚手架时,默认就会执行npm
    hidden: true            // 作为一个隐藏的命令
}).alias(i)


program.on('--help', function () {
    console.log('help info');
})

// debug模式实现
program.on('--debug', function () {
    process.env.LOG_LEVEL = program.debug ? 'verbose' : 'info';
    console.log(process.env.LOG_LEVEL);
})

// 对未知命令监听
program.on('command:*', function (obj) {
    console.error('unknown command', obj[0]);
    const availableCommand = program.commands.map(cmd => cmd.name);
    console.log('可用命令:' + availableCommand.join(""));

})


// 适用于所有命令的监听
program.arguments('<cmd> [options]')
    .description('test command', {
        cmd: 'command',
        options: 'options for command',
    })
    .action((cmd, options) => {
        console.log(cmd, options);
    })

program.addCommand(server)

program.parse(process.argv)


Previous Post
Nodejs多进程
Next Post
yargs常用方法