nodejs: commander,一个实现 cli 的工具

完整的 node.js 命令行解决方案
更新于: 2022-07-10 14:02:02

安装

npm i commander

使用 program

  • 实现单个命令
const { program } = require("commander");

program
  .option("--first")
  .option("-s, --separator <char>")
  .parse()
  .version("1.0.0");

console.log(program.opts(), program.args);
❯ node app arg1 --first
{ first: true } [ 'arg1' ]

使用 Command

  • 实现多命令(含子命令)
const { Command } = require('commander');
const program = new Command();

program
  .name('string-util')
  .description('CLI to some JavaScript string utilities')
  .version('0.8.0');

program.command('split')
  .description('Split a string into substrings and display as an array')
  .argument('<string>', 'string to split')
  .option('--first', 'display just the first substring')
  .option('-s, --separator <char>', 'separator character', ',')
  .action((str, options) => {
    const limit = options.first ? 1 : undefined;
    console.log(str.split(options.separator, limit));
  });

program.parse();
❯ node app.js 
Usage: string-util [options] [command]

CLI to some JavaScript string utilities

Options:
  -V, --version             output the version number
  -h, --help                display help for command

Commands:
  split [options] <string>  Split a string into substrings and display as an array
  help [command]            display help for command

program.parse

// 可以自定义 argv 传入
program.parse(process.argv);

参考