{"id":15745,"library":"option-parser","title":"Command-line Option Parser","description":"OptionParser is a JavaScript library designed for parsing command-line options, mimicking the functionality of POSIX `getopt`. It supports both short (`-x`) and long (`--long`) options, including combined short options (`-xxxyxxz`), and handles both required and optional argument values (e.g., `-x=Value`, `--long Value`). Key features include nearly automatic help message generation, flexible option handling through callbacks or direct access to option objects, and the ability to return any unparsed arguments. As of version 1.0.2, the library appears to be in a maintenance state, with its last update occurring in August 2021. While robust for its intended use, its release cadence is low, distinguishing it from more actively developed, modern CLI parsing solutions that may offer broader ecosystem support or different API paradigms.","status":"maintenance","version":"1.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/tests-always-included/option-parser","tags":["javascript","command-line","command","line","option","parser","flag","flags","getopt"],"install":[{"cmd":"npm install option-parser","lang":"bash","label":"npm"},{"cmd":"yarn add option-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add option-parser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This library is primarily CommonJS. Direct ESM import (e.g., `import` statements) is not officially supported and may require manual wrapping or a CJS loader configured for compatibility.","wrong":"import { OptionParser } from 'option-parser';","symbol":"OptionParser","correct":"const OptionParser = require('option-parser');"},{"note":"This is a method of the `OptionParser` instance; it's not a direct import.","symbol":"parser.addOption","correct":"parser.addOption('h', 'help', 'Display help')"},{"note":"This method is called on an `OptionParser` instance and processes `process.argv` by default, returning any arguments that were not parsed by the defined options.","symbol":"parser.parse","correct":"const unparsedArgs = parser.parse();"}],"quickstart":{"code":"const OptionParser = require('option-parser');\n\n// Simulate command line arguments for testing\n// In a real application, these would come directly from `process.argv`\nconst originalArgv = process.argv;\nprocess.argv = ['node', 'script.js', '-h', '--input', 'my_file.txt', '-f', '--debug=10', 'extra-arg1', 'extra-arg2'];\n\ntry {\n    const parser = new OptionParser();\n\n    let flagWasSet = false;\n    let inputFile = '/dev/stdin';\n    let debugLevel = 0;\n\n    // Add a standard help option\n    parser.addOption('h', 'help', 'Display this help message')\n        .action(() => {\n            console.log(parser.help());\n            process.exit(0);\n        });\n\n    // Toggle a flag with a callback\n    parser.addOption('f', null, 'Toggle a flag')\n        .action(function () {\n            flagWasSet = true;\n        });\n\n    // Pass a required value\n    parser.addOption('i', 'input', 'Specify an input file')\n        .argument('FILE')\n        .action(function (value) {\n            inputFile = value;\n        });\n\n    // Optional value using the returned option object\n    const debugOption = parser.addOption(null, 'debug',\n         'Sets the debug level (default is 5 if set without value)')\n        .argument('Level', false); // 'false' makes the argument optional\n\n    // Parse the command line options from process.argv\n    const unparsed = parser.parse();\n\n    // Retrieve debug level after parsing\n    if (debugOption.count()) {\n        debugLevel = debugOption.value() ? parseInt(debugOption.value(), 10) : 5;\n    }\n\n    console.log('--- Parsing Results ---');\n    console.log(`Help requested (-h/--help): ${parser.getOption('h').count() > 0}`);\n    console.log(`Flag was set (-f): ${flagWasSet}`);\n    console.log(`Input file (-i/--input): ${inputFile}`);\n    console.log(`Debug level (--debug): ${debugLevel}`);\n    console.log(`Unparsed arguments: ${JSON.stringify(unparsed)}`);\n    console.log('-----------------------');\n\n    // Optionally display help if not explicitly requested\n    if (parser.getOption('h').count() === 0) {\n        console.log('\\n--- Generated Help (truncated) ---');\n        console.log(parser.help().split('\\n').slice(0, 5).join('\\n')); // Show first 5 lines\n        console.log('...');\n    }\n\n} catch (error) {\n    console.error('An error occurred during parsing:', error.message);\n} finally {\n    // Restore original process.argv to avoid side effects in tests/other scripts\n    process.argv = originalArgv;\n}","lang":"javascript","description":"This quickstart demonstrates how to initialize the OptionParser, define various types of options (help, flag, required argument, optional argument), and parse simulated command-line input. It shows how to access parsed values through callbacks and option objects, and how to retrieve unparsed arguments."},"warnings":[{"fix":"Use `const OptionParser = require('option-parser');` for CommonJS projects. For ESM, you might need a wrapper or a CJS-compatible loader, or consider a different CLI parser with explicit ESM support.","message":"This library is primarily designed for CommonJS environments. While Node.js can sometimes load CommonJS modules in ESM contexts, direct `import` statements are not officially supported and may lead to unexpected behavior or require manual interoperability configuration. For modern ESM-first projects, consider alternatives.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review the project's GitHub repository for any unreleased updates or known issues. For critical applications, evaluate if a more actively maintained CLI parsing library is a better fit.","message":"The library has not been updated since August 2021 (version 1.0.2). This means it might not include fixes for newer Node.js runtime changes, security vulnerabilities discovered since then, or advancements in command-line parsing conventions or features that have emerged in more actively maintained libraries.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Implement robust data validation within your option `action` callbacks. For example, use `parseInt()` and check `isNaN()` for numeric arguments, and provide user-friendly error messages if validation fails.","message":"The README excerpt does not detail comprehensive built-in error handling for invalid option arguments (e.g., expecting a number but receiving a string). Users might need to implement custom validation within their `action` callbacks to ensure argument types and values are correct.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure `const OptionParser = require('option-parser');` is at the top of your file before instantiating the parser.","cause":"The `OptionParser` class was not correctly imported or required before use.","error":"ReferenceError: OptionParser is not defined"},{"fix":"Verify that you have correctly instantiated the parser using `const parser = new OptionParser();` before attempting to call its methods.","cause":"`addOption` is a method of an `OptionParser` instance, but it's being called on an undefined or incorrect object.","error":"TypeError: parser.addOption is not a function"},{"fix":"Double-check the short and long option names registered with `addOption` against the command-line arguments. Ensure correct casing and that all aliases (e.g., both '-i' and '--input') are explicitly defined.","cause":"Options are case-sensitive, or an expected option alias/format was not registered with `addOption`.","error":"Unexpected arguments are left in `unparsed` array even though they seem valid."}],"ecosystem":"npm"}