# npargv **Repository Path**: daoio/npargv ## Basic Information - **Project Name**: npargv - **Description**: Node.js解析process.argv选项的扩展。 - **Primary Language**: Unknown - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-09-19 - **Last Updated**: 2025-12-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # npargv 参数解析器 一个轻量级的 Node.js 扩展,用于快速、灵活地解析 `process.argv` 命令行参数。支持类型校验、默认值填充、子命令解析及严格模式。 ## 安装 ```bash npm i npargv ``` ## 快速上手 ```javascript 'use strict' const parseArgv = require('npargv') // 1. 定义参数规则 (Schema) const schema = { // 基础定义:指定类型和范围 '--port=': { name: 'port', alias: '-p', // 别名支持 type: 'int', min: 2000, max: 9000 }, // 正则匹配 '--host=': { name: 'host', match: /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/i, default: '127.0.0.1' }, // 简写模式:自动推断为 boolean,name 为 'verbose' '-v': 'verbose', // 简写模式:自动推断为 boolean,name 为 '-x' '-x': null, // 回调函数处理 '--ids': { name: 'ids', callback: (str) => str.split(',').filter(x => x.length > 0) }, // 位置参数引用 ($1 表示第一个非命令参数) '$1': { name: 'inputFile', type: 'string' } } // 2. 解析配置 (Options) const options = { strict: true, // 遇到错误是否立即停止并返回失败 autoDefault: true, // 是否自动填充默认值 commands: ['start', 'build'], // 支持的子命令 defaultCommand: 'start' // 默认子命令 } // 3. 执行解析 const ret = parseArgv(schema, options) console.log(ret) ``` **运行命令:** ```shell $ node app.js start --port=8080 -v --ids=1,2,3 config.json ``` **输出结果:** ```javascript { ok: true, // 解析是否成功 message: '', // 如果失败,返回第一个错误信息 errors: [], // 所有错误信息的数组 command: 'start', // 解析到的子命令 args: { // 解析后的参数对象 port: 8080, host: '127.0.0.1', // 使用了默认值 verbose: true, '-x': false, // 默认值 ids: ['1', '2', '3'], inputFile: 'config.json' }, list: [] // 未定义的非 Flag 参数(如多余的文件名) } ``` --- ## 核心功能详解 ### 1. 返回值说明 解析函数返回一个对象,包含以下字段: | 字段 | 类型 | 描述 | | :--- | :--- | :--- | | **ok** | boolean | 解析是否成功。在 `strict: true` 模式下,有任何错误即为 `false`。 | | **message** | string | 错误提示信息(兼容旧版 `errmsg`),若无错误为空字符串。 | | **errors** | array | 包含解析过程中产生的所有错误信息的数组。 | | **args** | object | 解析后的键值对结果。 | | **command** | string | 识别到的子命令(若配置了 commands)。 | | **list** | array | 未被定义的普通参数(不以 `-` 开头的内容,或被转义的内容)。 | > **注意**:根据最新代码逻辑,**未定义的 Flag 参数**(以 `-` 开头但未在 Schema 中定义的参数)会被忽略,不会出现在 `args` 或 `list` 中。 ### 2. 参数定义 (Schema) `schema` 对象中的 Key 通常是命令行参数的触发标识(如 `--port` 或 `--port=`),Value 是配置对象。 #### 配置项支持 | 选项 | 类型 | 描述 | | :--- | :--- | :--- | | **type** | string | 数据类型。支持 `int`/`number`, `float`, `string`, `bool`/`boolean`。若未指定,会尝试自动推断。 | | **name** | string | 解析结果 `args` 中的属性名。 | | **alias** | string | 参数别名,例如 `-p` 指向 `--port`。 | | **default** | any | 默认值。若解析出错(且非严格模式)或未输入,则使用此值。 | | **min** | number | 最小值限制(仅对数字类型有效)。 | | **max** | number | 最大值限制(仅对数字类型有效)。 | | **match** | RegExp | 正则表达式校验(会自动将 type 推断为 string)。 | | **callback** | function | 自定义处理函数。接收原始值,若返回非 `undefined`,则替换解析值。 | #### 简写模式 * **字符串简写**:`{ '-v': 'verbose' }` 等价于 `{ '-v': { name: 'verbose', type: 'boolean', default: false } }` * **空简写**:`{ '--flag': null }` 或 `{ '--flag': {} }` 等价于 `{ '--flag': { name: '--flag', type: 'boolean' } }` #### 类型推断规则 (Type Inference) 若未显式指定 `type`,程序按以下顺序自动推断: 1. 若 Key 包含 `=` (如 `--port=`),推断为 **string**。 2. 若配置了 `match` 或 `callback`,推断为 **string**。 3. 若配置了 `min` 或 `max`,推断为 **int**。 4. 若配置了 `default`,推断为 `default` 值的类型。 5. 默认推断为 **boolean**。 ### 3. 解析选项 (Options) `parseArgv` 的第二个参数用于控制解析行为: ```javascript parseArgv(schema, { strict: true, // 严格模式 (默认 true) autoDefault: true, // 自动生成默认值 (默认 true) commands: [], // 子命令列表 defaultCommand: '', // 缺省子命令 argv: process.argv // 自定义参数源 (用于测试或非 node 环境) }) ``` #### strict 严格模式 * `true` (默认):一旦遇到类型错误、范围错误或缺少必要参数,立即停止解析,`ok` 返回 `false`,并返回错误信息。 * `false`:遇到错误时会将错误推入 `errors` 数组,但不会中断解析。出错的参数将保留其默认值(如果有),解析继续进行。 #### autoDefault 自动默认值 开启后,程序会根据 `type` 自动填充 `default` 值(仅在 schema 中未定义 default 时生效): * `number`/`int`/`float`: 默认为 `min` (若存在) 或 `0`。 * `string`: 默认为 `''` (空字符串)。 * `bool`: 默认为 `false`。 ### 4. 子命令支持 通过配置 `commands` 数组启用子命令模式。 ```javascript let options = { commands: ['create', 'delete', 'update'], defaultCommand: 'create' } ``` * **解析逻辑**:程序会检查脚本后的第一个参数。如果是 `commands` 列表中的一项,则将其记录在返回对象的 `command` 字段中,并从下一个参数开始解析 Flag。 * **位置参数影响**:若使用了子命令,位置参数 `$1` 指向子命令**之后**的第一个参数。 ### 5. 位置引用参数 ($1, $2...) 支持直接解析固定位置的参数。Key 使用 `$N` 格式(N 从 1 开始)。 ```javascript const schema = { // $1 是第一个非 Flag 参数 '$1': { name: 'source', type: 'string' }, // $2 是第二个 '$2': { name: 'dest', type: 'string' } } ``` * **注意**:`$N` 对应的是实际参数列表中的顺序。如果启用了子命令,`$1` 是子命令后的第一个参数。 ### 6. 转义与未知参数 * **转义**:如果需要传递以 `-` 开头的普通字符串(例如文件名名为 `-file`),可以使用 `\` 转义,如 `\-file`。解析器会将其还原为 `-file` 并放入 `list` 数组中。 * **未知参数**:不以 `-` 开头的参数,如果未被位置引用(`$N`)捕获,会被放入 `list` 数组。 --- ## 常见示例 ### 场景:Web 服务器配置 ```javascript const schema = { // 端口:整数,2000-9000,默认 3000 '--port': { type: 'int', min: 2000, max: 9000, default: 3000 }, // 开启调试:布尔值 '--debug': 'debug', // 数据库地址:正则校验 '--db': { match: /^mysql:\/\//, name: 'databaseUrl' } }; const result = parseArgv(schema, { strict: true }); if (!result.ok) { console.error('参数错误:', result.message); process.exit(1); } console.log('启动服务:', result.args); ``` ### 场景:文件处理工具 (非严格模式) ```javascript const schema = { '$1': { name: 'file' }, '--retry': { type: 'int', default: 3 } }; // strict: false 允许参数出错时不中断,使用默认值 const result = parseArgv(schema, { strict: false }); if (result.errors.length > 0) { console.warn('警告:部分参数不合法,已使用默认值:', result.errors); } // 即使 --retry=abc 输入错误,args.retry 仍为 3 runProcess(result.args); ```