Skip to content

Instantly share code, notes, and snippets.

@bit-cmdr
Last active November 27, 2017 19:14
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 bit-cmdr/48b7d82ad93fe9e3043d61e842c0ebe3 to your computer and use it in GitHub Desktop.
Save bit-cmdr/48b7d82ad93fe9e3043d61e842c0ebe3 to your computer and use it in GitHub Desktop.
Parse Node Arguments with named arguments
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);
@bit-cmdr
Copy link
Author

Invoked as:

node parse-arguments --username alexander --password Password1

opts will contain:

{
  username: 'alexander',
  password: 'Password1'
}

That's just an example password, if it matches your real password. Change your password.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment