Skip to content

Instantly share code, notes, and snippets.

@darkwebdev
Last active September 13, 2019 13:09
Show Gist options
  • Save darkwebdev/e347d90a608820c30da66c1217702236 to your computer and use it in GitHub Desktop.
Save darkwebdev/e347d90a608820c30da66c1217702236 to your computer and use it in GitHub Desktop.
Convert script arguments to an object (ES6)
const longArgs = arg => {
const [ key, value ] = arg.split('=');
return { [key.slice(2)]: value || true }
};
const flags = arg => [...arg.slice(1)].reduce((flagObj, f) => ({ ...flagObj, [f]: true }), {});
module.exports = () =>
process.argv
.slice(2)
.reduce((args, arg) => ({
...args,
...((arg.startsWith('--') && longArgs(arg)) || (arg[0] === '-' && flags(arg)))
}), {});
// usage:
// const args = require('./args')();
// args.help === true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment