Optional
defaultValue: T默认值
配置项
参数的值类型,默认为 'string'
参数的值自定义验证函数,返回 true 或错误信息字符串
参数别名,支持短参数
数组类型的分隔符,默认为 ','
是否必需参数
解析后的参数值
// 基本用法
const name = getCommandParam('name', 'default');
// node script.js --name John
// 数字类型
const port = getCommandParam('port', 3000, { valueType: 'number' });
// node script.js --port 8080
// 布尔标志
const debug = getCommandParam('debug', false, { valueType: 'boolean' });
// node script.js --debug
// 数组类型
const files = getCommandParam('files', [], { valueType: 'array' });
// node script.js --files file1.txt,file2.txt,file3.txt
// 带验证
const email = getCommandParam('email', '', {
validator: (value) => {
if (typeof value === 'string' && value.includes('@')) {
return true;
}
return 'Email must contain @ symbol';
}
});
// 必需参数
const apiKey = getCommandParam('api-key', undefined, {
required: true,
alias: 'k'
});
// node script.js --api-key abc123 或 -k abc123
// 批量解析
const config = parseCommandParams({
host: { defaultValue: 'localhost' },
port: { valueType: 'number', defaultValue: 3000 },
ssl: { valueType: 'boolean', defaultValue: false },
workers: { valueType: 'array', defaultValue: ['main'] }
});
参数名(支持 --param 或 -p 格式)