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
const program = require('commander');
const chalk = require('chalk');

async function run() {
program
.version(await require('../package.json').version)
.option('-w, --wheight','rename the img with width and height')
.option('-c, --compress','compress pictures')

program.on('--help',() => {
console.log(
chalk.green(
'this is a img tool'
)
)
})

program.parse(process.argv)

if(program.wheight){
console.log('wheight')
}

console.log(program.version())

}

run()

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
iMac:img_tools $ imgwh -w
wheight
1.0.0

iMac:img_tools $ imgwh --help
Usage: imgwh [options]

Options:
-V, --version output the version number
-w, --wheight rename the img with width and height
-c, --compress compress pictures
-h, --help output usage information
this is a img tool

api

  1. .version
    定义命令程序版本号
    .version(<string>)

  2. .option
    定义命令选项
    .option(flags, description, [fn], defaultValue)
    flags: 分为长短标识,中间用逗号、竖线或者空格分割。标志后面可跟必须参数或可选参数,前者用 <> 包含,后者用 [] 包含

    1
    2
    3
    "-p, --pepper"
    "-p|--pepper"
    "-p --pepper"

examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 简单命令默认为true
program.option('-C, --no-cheese', 'remove cheese');

program.cheese
// => true

--no-cheese
program.cheese
// => false

// 必需参数
program.option('-C, --chdir <path>', 'change the working directory');

--chdir /tmp
program.chdir
// => "/tmp"

// 可选参数
program.option('-c, --cheese [type]', 'add cheese [marble]');
  1. .command
    添加命令名称
    .command('name', 'description', opts)
    1
    命令后面可跟用 <> 或 [] 包含的参数,命令后面传入的参数会被传入到 action 的回调函数
1
2
3
4
5
6
7
program
.command('setup')
.option('--w', 'this is test')
.description('run remote setup commands')
.action(function(option) {
console.log(option.w);
});
1
2
iMac:img_tools $ imgwh setup --w a
a
  1. .action
    定义命令的回调

  2. .description
    定义命令的描述

  3. .parse
    用于解析process.argv,设置options以及触发commands