Skip to content

Instantly share code, notes, and snippets.

@trevorhreed
Last active January 20, 2022 23:34
Show Gist options
  • Save trevorhreed/7710cdf5f9df8fd7c7ee700f421c54cd to your computer and use it in GitHub Desktop.
Save trevorhreed/7710cdf5f9df8fd7c7ee700f421c54cd to your computer and use it in GitHub Desktop.
Turns `process.argv` into an array-like object with fixed position arguments indexed by number and named arguments indexed by key.
/**
* Simple command line argument parser
*
* An instance of Args is an array-like
* object that contains a list of fixed
* and named arguments
*
* Given command line args of:
*
* node args.js command -a --param=value
*
* This code...
*
* ```javascript
* const args = new Args()
* console.dir(args)
* ```
*
* ...will produce this output:
*
* ```
* Args(2) [
* 'topic',
* 'command',
* f: true,
* l: true,
* a: true,
* g: true,
* param1: 'value1',
* param2: true
* ]
* ```
*/
export class Args extends Array {
constructor(
args = process.argv.slice(2)
) {
super()
for (let i = 0, al = args.length; i < al; i++) {
const item = args[i]
const isNamed = item.startsWith('-')
const isShortForm = isNamed && item.charAt(1) !== '-'
if (isNamed) {
// named
let key = '', value = true
for (let j = 0, il = item.length; j < il; j++) {
const c = item.charAt(j)
if (!key && c === '-') continue
if (value === true && c === '=') value = ''
else if (value === true) key += c
else value += c
}
if (value === true && isShortForm) {
key.split('').forEach(k => {
this[k] = value
})
} else {
this[key] = value
}
} else {
// fixed
this.push(item)
}
}
}
}
if (import.meta.url === `file://${process.argv[1]}`) {
/**
* Hint: try running with the following command:
*
* node args.js topic command -flag --param1=value1 --param2
*/
const args = new Args()
console.dir(args)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment