/**
* Parses command line arguments as arrays, supporting older Node.js versions.
*
* @param {string[]} args The command line arguments.
* @returns {object} An object where keys are argument names and values are arrays of corresponding values.
*/
function parseArgs(args) {
const parsedArgs = {};
const argIndex = 0;
while (argIndex < args.length) {
const arg = args[argIndex];
if (arg.startsWith('--')) {
const argName = arg.slice(2); // Remove the leading '--'
const values = [];
let i = argIndex + 1;
while (i < args.length && !args[i].startsWith('--')) {
values.push(args[i]);
i++;
}
parsedArgs[argName] = values;
argIndex = i; // Skip the values of the argument
} else {
// Handle positional arguments (if any) - not strictly required but good practice
if (!parsedArgs['']) {
parsedArgs[''] = [arg]; // Store positional arguments under an empty string key.
} else {
parsedArgs[''].push(arg); //Append to existing positional arguments.
}
argIndex++;
}
}
return parsedArgs;
}
//Example Usage (for testing)
//const args = ['--name', 'John', '--age', '30', 'city', 'New York'];
//const parsed = parseArgs(args);
//console.log(parsed);
Add your comment