1. /**
  2. * Parses command line arguments as arrays, supporting older Node.js versions.
  3. *
  4. * @param {string[]} args The command line arguments.
  5. * @returns {object} An object where keys are argument names and values are arrays of corresponding values.
  6. */
  7. function parseArgs(args) {
  8. const parsedArgs = {};
  9. const argIndex = 0;
  10. while (argIndex < args.length) {
  11. const arg = args[argIndex];
  12. if (arg.startsWith('--')) {
  13. const argName = arg.slice(2); // Remove the leading '--'
  14. const values = [];
  15. let i = argIndex + 1;
  16. while (i < args.length && !args[i].startsWith('--')) {
  17. values.push(args[i]);
  18. i++;
  19. }
  20. parsedArgs[argName] = values;
  21. argIndex = i; // Skip the values of the argument
  22. } else {
  23. // Handle positional arguments (if any) - not strictly required but good practice
  24. if (!parsedArgs['']) {
  25. parsedArgs[''] = [arg]; // Store positional arguments under an empty string key.
  26. } else {
  27. parsedArgs[''].push(arg); //Append to existing positional arguments.
  28. }
  29. argIndex++;
  30. }
  31. }
  32. return parsedArgs;
  33. }
  34. //Example Usage (for testing)
  35. //const args = ['--name', 'John', '--age', '30', 'city', 'New York'];
  36. //const parsed = parseArgs(args);
  37. //console.log(parsed);

Add your comment