1. /**
  2. * Parses command-line options and stores them in an object.
  3. * This is for development use only.
  4. *
  5. * @param {string[]} args The command-line arguments.
  6. * @returns {object} An object containing the parsed options.
  7. */
  8. function parseCommandLineOptions(args) {
  9. const options = {}; // Initialize an empty object to store options
  10. let i = 0;
  11. while (i < args.length) {
  12. if (args[i] === '-h' || args[i] === '--help') {
  13. printHelp(); // Call help function if -h or --help is found
  14. return options; // Return empty options after printing help
  15. } else if (args[i].startsWith('--')) {
  16. const optionName = args[i].substring(2); // Extract option name
  17. if (args[i + 1] !== undefined) {
  18. const optionValue = args[i + 1]; // Extract option value
  19. options[optionName] = optionValue; // Store option and value
  20. i += 2; // Skip option and value
  21. } else {
  22. options[optionName] = true; // Store option as a boolean if no value is provided
  23. i++; // Skip option
  24. }
  25. } else {
  26. // Non-option arguments are ignored
  27. i++;
  28. }
  29. }
  30. return options; // Return the parsed options object
  31. }
  32. /**
  33. * Prints help information.
  34. */
  35. function printHelp() {
  36. console.log('Usage: script.js [-h|--help] [option1] [option2]');
  37. console.log('Options:');
  38. console.log(' -h, --help Show this help message');
  39. console.log(' option1 Value for option1');
  40. console.log(' option2 Value for option2');
  41. }
  42. // Example usage (for testing)
  43. if (require.main === module) {
  44. const args = process.argv.slice(2); // Get command-line arguments
  45. const parsedOptions = parseCommandLineOptions(args); // Parse options
  46. console.log(parsedOptions); // Output the parsed options object
  47. }

Add your comment