Skip to content

Instantly share code, notes, and snippets.

@crashmax-dev
Created December 27, 2023 14:08
Show Gist options
  • Save crashmax-dev/9bb61d0f485580da88635ecf261eb7c7 to your computer and use it in GitHub Desktop.
Save crashmax-dev/9bb61d0f485580da88635ecf261eb7c7 to your computer and use it in GitHub Desktop.
function parseArgs(args) {
const parsedArgs = {};
function parseByFlag(args, flag) {
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('--')) break
if (!parsedArgs[flag]) parsedArgs[flag] = []
parsedArgs[flag].push(args[i])
}
}
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('--')) {
const flag = args[i].slice(2)
const argsWithoutFlag = args.slice(i + 1)
parseByFlag(argsWithoutFlag, flag)
}
}
return parsedArgs
}
const args = process.argv.slice(2);
const parsedArgs = parseArgs(args);
console.log(parsedArgs)
// node test.js --directory a b --test c
// { directory: [ 'a', 'b' ], test: [ 'c' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment