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 提供了从基础到高级的完整命令行参数解析方案:
- 简单直观的参数解析
- 丰富的参数类型支持(布尔值、计数等)
- 强大的参数验证功能
- 完善的帮助系统构建
- 与其他工具的良好集成能力
通过本文的示例,开发者可以快速掌握 Yargs 的核心功能,构建出专业级的命令行应用。无论是简单的脚本还是复杂的 CLI 工具,Yargs 都能提供优雅的解决方案。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考