easy-arg

一个命令行解析模块

Usage no npm install needed!

<script type="module">
  import easyArg from 'https://cdn.skypack.dev/easy-arg';
</script>

README

Easy-Arg

用于方便的解析用户输入的命令行参数,

install

npm install --save easy-arg

API

// 引入并创建一个实例
const EasyArg = require('ease-arg');
/**
 * 包括两个参数,第一个参数是标识这个实例的字符串
 * 第二个参数是一个对象,传入一个unexpectedCommand函数,当我们遇到未预期的命令时,就会调用这个函数
 */
const options = {unexpectedCommand: (command) => {console.log(command + '没有被add过')}}
const easyArg = new EasyArg('hello', options);

// 获取这个实例的name
console.log(easyArg.name);

add

添加一个命令

// 添加init命令,用户输入在init后的参数会以数组的形式传入
// 只有add过的字符串,我们才认为是命令,否则一律认为是参数

easyArg.add('init', (input) => {
  console.log('input', input);
});

start

开始解析

// 参数为用户输入的所有命令以及参数组成的对象
easyArg.start((inputCommands) => {
  console.log(inputCommands);
});

事件

支持事件的方式触发

// 每当匹配到一个命令的时候,就会触发,接受命令的值以及命令的参数
easyArg.on('command', ({command, args}) => {
  if (command === '-b') {
    console.log(args);
  }
});

Example

const EasyArg = require('easy-arg');

/**
 * 包括两个参数,第一个参数是标识这个实例的字符串
 * 第二个参数是一个对象,传入一个unexpectedCommand函数,当我们遇到未预期的命令时,就会调用这个函数
 */
const options = {unexpectedCommand: (command) => {console.log(command + '没有被add过')}}
const easyArg = new EasyArg('hello', options);
easyArg.add('init', (input) => {
  console.log('input', input);
});
easyArg.add('fad');
easyArg.add('-b');

// 监听每一个匹配到的命令
easyArg.on('command', ({command, args}) => {
  if (command === '-b') {
    console.log(args);
  }
});

// 开始匹配(必须要写)可以接受一个回调函数,函数的参数是输入的所有“命令”(指被add过的命令)
easyArg.start((inputCommands) => {
  console.log(inputCommands);
});

// 返回这个实例的name
console.log(easyArg.name);