Created
August 5, 2016 16:57
-
-
Save binoculars/cd73f914ee3a7aba8e374fbcdb0b73de to your computer and use it in GitHub Desktop.
Node.js quick CLI arguments parser for key-value pair arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Takes arguments in the form of --arg-name value and puts them into an object (argMap). | |
* Argument keys begin with double hyphens and additional hyphens are converted to camelCase. | |
* | |
* E.g. `node quick-argument-parser.js --test-arg1 'value1' --test-arg2 'value2'` will create argMap with the value: | |
* ``` | |
* { | |
* testArg1: 'value1', | |
* testArg2: 'value2' | |
* } | |
* ``` | |
* Node.js >= 4 | |
*/ | |
const args = process.argv.slice(2); | |
const argMap = {}; | |
if (args.length % 2) | |
throw new Error('Invalid number of arguments'); | |
for (let i = 0; i < args.length; i += 2) { | |
let key = args[i]; | |
if (!/^--([a-z]+-)*[a-z]+$/g.test(key)) | |
throw new Error('Invalid argument name'); | |
key = key | |
.replace(/^--/, '') | |
.replace(/-([a-z])/g, g => g[1].toUpperCase()); | |
argMap[key] = args[i + 1]; | |
} | |
// use argMap here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment