Last active
June 23, 2023 15:59
-
-
Save RyadPasha/24bd527f86355579f2d812eefd4fa797 to your computer and use it in GitHub Desktop.
Parse command-line arguments in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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