Commander常见用法

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/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)