Last active
November 27, 2017 19:14
-
-
Save bit-cmdr/48b7d82ad93fe9e3043d61e842c0ebe3 to your computer and use it in GitHub Desktop.
Parse Node Arguments with named 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
function parseArgs(args) { | |
let parsed = {}; | |
try { | |
parsed = Object.assign( | |
...args | |
.slice(2) | |
.reduce((l, r) => { | |
if (!Array.isArray(l)) l = [[l, r]]; | |
else if (r.startsWith('--')) l.push([r]); | |
else l[l.length - 1].push(r); | |
return l; | |
}) | |
.map(p => ({ [p[0].substring(2)]: p[1] })) | |
); | |
} catch (e) { | |
console.error('Unknown argument passed', e); | |
} | |
return parsed; | |
} | |
const opts = parseArgs(process.argv); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Invoked as:
opts will contain:
That's just an example password, if it matches your real password. Change your password.