Skip to content

Instantly share code, notes, and snippets.

@RyadPasha
Last active June 23, 2023 15:59
Show Gist options
  • Save RyadPasha/24bd527f86355579f2d812eefd4fa797 to your computer and use it in GitHub Desktop.
Save RyadPasha/24bd527f86355579f2d812eefd4fa797 to your computer and use it in GitHub Desktop.
Parse command-line arguments in Node.js
/**
* Parse command-line arguments in the format:
* ● --arg_name=arg_value
* ● -arg_name=arg_value
* ● arg_name=arg_value
*
* @author Mohamed Riyad <m@ryad.me>
*
* @param {string[]} [args] - The array of command-line arguments.
* @returns {Object} An object containing the parsed arguments.
*/
function parseArguments(args = null) {
args = args || process.argv.slice(2)
const argPattern = /^-?-?([a-zA-Z][\w-]*)=(.+)$/
const parsedArgs = {}
for (const arg of args) {
const match = arg.match(argPattern)
if (match) {
const argName = match[1]
const argValue = match[2]
parsedArgs[argName] = argValue
}
}
return parsedArgs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment