Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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);
Owner

bit-cmdr commented Nov 27, 2017

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