NodeJS Commander 结构化子命令

Leh*_*hks 2 node.js node-commander

我是指挥官的新手,我正在尝试实现这样的命令树:

|- build
|    |- browser (+ options)
|    |- cordova (+ options)
|    |- no subcommands, just options
|- config
|    |- create (+ options)
Run Code Online (Sandbox Code Playgroud)

是否可以将这些命令拆分成多个文件,例如有点像这样:

中央档案:

|- build
|    |- browser (+ options)
|    |- cordova (+ options)
|    |- no subcommands, just options
|- config
|    |- create (+ options)
Run Code Online (Sandbox Code Playgroud)

构建命令的文件:

program.command('browser').description(...);
program.command('cordova').description(...);
program.option(...);
Run Code Online (Sandbox Code Playgroud)

配置命令的文件:

program.command('create').description(...);
Run Code Online (Sandbox Code Playgroud)

我知道 Git 风格的子命令,但这些似乎需要可执行文件(我只有常规的 JS 文件)

Kim*_*m T 12

他们的文档中有一个示例:

const commander = require('commander');
const program = new commander.Command();
const brew = program.command('brew');
brew
  .command('tea')
  .action(() => {
    console.log('brew tea');
  });
brew
  .command('coffee')
  .action(() => {
    console.log('brew coffee');
  });
Run Code Online (Sandbox Code Playgroud)

输出示例:

$ node nestedCommands.js brew tea
brew tea
Run Code Online (Sandbox Code Playgroud)

https://github.com/tj/commander.js/blob/master/examples/nestedCommands.js


sha*_*awn 6

Commander 明确支持带有.js文件扩展名的独立子命令“可执行”文件,无需设置文件权限等以使其在命令行上直接执行。

下午.js

const commander = require('commander');
const program = new commander.Command();
program
  .command('build', 'build description')
  .command('config', 'config description')
  .parse(process.argv);
Run Code Online (Sandbox Code Playgroud)

pm-config.js

const commander = require('commander');
const program = new commander.Command();
program
  .command('create')
  .description('create description')
  .action(() => {
    console.log('Called create');
  });
program.parse(process.argv);
Run Code Online (Sandbox Code Playgroud)
$ node pm.js config create
Called create
Run Code Online (Sandbox Code Playgroud)