Skip to content

Instantly share code, notes, and snippets.

@farskid
Forked from binoculars/quick-argument-parser.js
Created March 16, 2020 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farskid/47e0f65f9975e7cd5ae8b88fd665c81b to your computer and use it in GitHub Desktop.
Save farskid/47e0f65f9975e7cd5ae8b88fd665c81b to your computer and use it in GitHub Desktop.
Node.js quick CLI arguments parser for key-value pair arguments
/**
* 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