Yargs 命令行参数解析工具实战指南

Yargs 命令行参数解析工具实战指南

yargs yargs the modern, pirate-themed successor to optimist. yargs 项目地址: https://gitcode.com/gh_mirrors/ya/yargs

前言

Yargs 是一个强大的 Node.js 命令行参数解析工具,它能帮助开发者轻松构建复杂的命令行应用。本文将深入解析 Yargs 的核心功能,通过实际示例展示其强大之处。

基础使用

简单参数解析

Yargs 最基本的功能是将命令行参数解析为 JavaScript 对象:

#!/usr/bin/env node
import yargs from 'yargs';
const argv = yargs(process.argv.slice(2)).parse();

if (argv.ships > 3 && argv.distance < 53.5) {
  console.log('Plunder more riffiwobbles!');
} else {
  console.log('Retreat from the xupptumblers!');
}

执行示例:

$ ./plunder.js --ships=4 --distance=22
Plunder more riffiwobbles!

$ ./plunder.js --ships 12 --distance 98.7
Retreat from the xupptumblers!

短参数与布尔值

Yargs 支持短参数和布尔值参数,甚至可以组合短参数:

#!/usr/bin/env node
import yargs from 'yargs';
const argv = yargs(process.argv.slice(2)).parse();

if (argv.s) {
  process.stdout.write(argv.fr ? 'Le perroquet dit: ' : 'The parrot says: ');
}
console.log((argv.fr ? 'couac' : 'squawk') + (argv.p ? '!' : ''));

执行示例:

$ ./bool.cjs -s
The parrot says: squawk

$ ./bool.cjs -sp
The parrot says: squawk!

$ ./bool.cjs -sp --fr
Le perroquet dit: couac!

高级功能

非连字符参数处理

Yargs 通过 argv._ 属性访问非连字符参数:

#!/usr/bin/env node
import yargs from 'yargs';
const argv = yargs(process.argv.slice(2)).parse();
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);

执行示例:

$ ./nonopt.mjs -x 6.82 -y 3.35 rum
(6.82,3.35)
[ 'rum' ]

$ ./nonopt.mjs "me hearties" -x 0.54 yo -y 1.12 ho
(0.54,1.12)
[ 'me hearties', 'yo', 'ho' ]

参数计数功能

Yargs 可以统计布尔参数的出现次数,实现日志级别控制:

#!/usr/bin/env node
import yargs from 'yargs';
const argv = yargs(process.argv.slice(2))
  .count('verbose')
  .alias('v', 'verbose')
  .parse();

VERBOSE_LEVEL = argv.verbose;

function WARN() {
  VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments);
}
function INFO() {
  VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments);
}
function DEBUG() {
  VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments);
}

WARN('Showing only important stuff');
INFO('Showing semi-important stuff too');
DEBUG('Extra chatty mode');

执行示例:

$ node count.mjs -v
Showing only important stuff
Showing semi-important stuff too

$ node count.mjs -vv
Showing only important stuff
Showing semi-important stuff too
Extra chatty mode

参数验证与帮助系统

必填参数验证

Yargs 可以强制要求某些参数必须提供:

#!/usr/bin/env node
import yargs from 'yargs';
var argv = yargs(process.argv.slice(2))
  .usage('Usage: $0 -w [num] -h [num]')
  .demandOption(['w', 'h'])
  .parse();

console.log('The area is:', argv.w * argv.h);

执行示例:

$ ./area.js -w 55 -h 11
The area is: 605

$ node ./area.js -w 4.91 -w 2.51
Usage: area.js -w [num] -h [num]

Options:
  -w  [required]
  -h  [required]

Missing required arguments: h

构建完善的帮助系统

Yargs 提供了完整的帮助系统构建功能:

#!/usr/bin/env node
import yargs from 'yargs';
import {createReadStream} from 'node:fs';
const argv = yargs(process.argv.slice(2))
  .usage('Usage: $0 <command> [options]')
  .command('count', 'Count the lines in a file')
  .example('$0 count -f foo.js', 'count the lines in the given file')
  .alias('f', 'file')
  .nargs('f', 1)
  .describe('f', 'Load a file')
  .demandOption(['f'])
  .help('h')
  .alias('h', 'help')
  .epilog('copyright 2019')
  .parse();

交互式命令行

Yargs 可以与 Inquirer 等交互式工具结合使用:

import yargs from 'yargs';
import inquirer from 'inquirer';

const sing = () => console.log('🎵 Oy oy oy');

const askName = async () => {
  const answers = await inquirer.prompt([
    {
      message: 'What is your name?',
      name: 'name',
      type: 'string',
    },
  ]);

  console.log(`Hello, ${answers.name}!`);
};

const argv = yargs(process.argv.splice(2))
  .command('ask', 'use inquirer to prompt for your name', () => {}, askName)
  .command('sing', 'a classic yargs command without prompting', () => {}, sing)
  .demandCommand(1, 1, 'choose a command: ask or sing')
  .strict()
  .help('h')
  .parse();

总结

Yargs 提供了从基础到高级的完整命令行参数解析方案:

  1. 简单直观的参数解析
  2. 丰富的参数类型支持(布尔值、计数等)
  3. 强大的参数验证功能
  4. 完善的帮助系统构建
  5. 与其他工具的良好集成能力

通过本文的示例,开发者可以快速掌握 Yargs 的核心功能,构建出专业级的命令行应用。无论是简单的脚本还是复杂的 CLI 工具,Yargs 都能提供优雅的解决方案。

yargs yargs the modern, pirate-themed successor to optimist. yargs 项目地址: https://gitcode.com/gh_mirrors/ya/yargs

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

昌隽艳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值