UNPKG

nyx_server

Version:

Node内容发布

82 lines (70 loc) 1.93 kB
/** * 1. --key 为参数名全写 * 2. -shortkey 为参数名缩写 * 3. 参数名缩写为单字母,如果遇到多字母,则将其分开为单字母 * 4. 参数值为跟在参数名空格后的字符串,只能有一个,多余的字符串会放在remain数组中 * 5. 参数 -h 和 --help都会转换为 help。 * 6. 参数值有三中类型 字符串 数字 布尔值 */ var defaultValue = true; var isKey = function (value) { return /^--/.test(value); }; var isShortKey = function (value) { return /^-/.test(value); }; var map = { '-h': 'help', '--help': 'help', }; var setValue = function (obj, key, value) { if (obj.hasOwnProperty(key)) { if (Array.isArray(obj[key])) { obj[key].push(value); } else { obj[key] = [obj[key], value]; } } else { obj[key] = value; } }; var parse = function (argv) { var options = { }; var shortKeys = {}; var remains = []; var value; var nextValue; var result; var key; for (var i = 0, iLen = argv.length; i < iLen; i++) { value = argv[i]; nextValue = argv[i + 1]; if (isKey(value)) { result = isKey(nextValue) || isShortKey(nextValue) ? defaultValue : (i++, nextValue ? nextValue : defaultValue); key = value.replace(/^--/,''); setValue(options, key, result); } else if (isShortKey(value)) { result = isKey(nextValue) || isShortKey(nextValue) ? defaultValue : (i++, nextValue ? nextValue : defaultValue); value.replace(/^-/, '').split('').forEach(function (key) { setValue(shortKeys, key, result); }); } else { remains.push(value); } } return { options: options, shortKeys: shortKeys, remains: remains }; }; module.exports = function (argv) { var commandName = argv.shift(); if (map[commandName]) { commandName = map[commandName]; } var result = parse(argv); result.name = commandName; return result; };