Registry / testing / option-parser

option-parser

JSON →
library1.0.2jsnpmunverified

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.

npm install option-parser
INSTALL
IMPORT
SIG · OPTION-PARSER
O
option-parser
testingjavascriptv1.0.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

OptionParser
const OptionParser = require('option-parser');
import { OptionParser } from 'option-parser';
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.
parser.addOption
parser.addOption('h', 'help', 'Display help')
This is a method of the `OptionParser` instance; it's not a direct import.
parser.parse
const unparsedArgs = parser.parse();
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.

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.

const OptionParser = require('option-parser'); // Simulate command line arguments for testing // In a real application, these would come directly from `process.argv` const originalArgv = process.argv; process.argv = ['node', 'script.js', '-h', '--input', 'my_file.txt', '-f', '--debug=10', 'extra-arg1', 'extra-arg2']; try { const parser = new OptionParser(); let flagWasSet = false; let inputFile = '/dev/stdin'; let debugLevel = 0; // Add a standard help option parser.addOption('h', 'help', 'Display this help message') .action(() => { console.log(parser.help()); process.exit(0); }); // Toggle a flag with a callback parser.addOption('f', null, 'Toggle a flag') .action(function () { flagWasSet = true; }); // Pass a required value parser.addOption('i', 'input', 'Specify an input file') .argument('FILE') .action(function (value) { inputFile = value; }); // Optional value using the returned option object const debugOption = parser.addOption(null, 'debug', 'Sets the debug level (default is 5 if set without value)') .argument('Level', false); // 'false' makes the argument optional // Parse the command line options from process.argv const unparsed = parser.parse(); // Retrieve debug level after parsing if (debugOption.count()) { debugLevel = debugOption.value() ? parseInt(debugOption.value(), 10) : 5; } console.log('--- Parsing Results ---'); console.log(`Help requested (-h/--help): ${parser.getOption('h').count() > 0}`); console.log(`Flag was set (-f): ${flagWasSet}`); console.log(`Input file (-i/--input): ${inputFile}`); console.log(`Debug level (--debug): ${debugLevel}`); console.log(`Unparsed arguments: ${JSON.stringify(unparsed)}`); console.log('-----------------------'); // Optionally display help if not explicitly requested if (parser.getOption('h').count() === 0) { console.log('\n--- Generated Help (truncated) ---'); console.log(parser.help().split('\n').slice(0, 5).join('\n')); // Show first 5 lines console.log('...'); } } catch (error) { console.error('An error occurred during parsing:', error.message); } finally { // Restore original process.argv to avoid side effects in tests/other scripts process.argv = originalArgv; }
Debug
Known issues
gotchaThis 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.
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.
affects: >=1.0.0
gotchaThe 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.
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.
affects: >=1.0.0
gotchaThe 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.
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.
affects: >=1.0.0
Errors
Common errors & fixes
ReferenceError: OptionParser is not defined
The `OptionParser` class was not correctly imported or required before use.
fix
Ensure `const OptionParser = require('option-parser');` is at the top of your file before instantiating the parser.
TypeError: parser.addOption is not a function
`addOption` is a method of an `OptionParser` instance, but it's being called on an undefined or incorrect object.
fix
Verify that you have correctly instantiated the parser using `const parser = new OptionParser();` before attempting to call its methods.
Unexpected arguments are left in `unparsed` array even though they seem valid.
Options are case-sensitive, or an expected option alias/format was not registered with `addOption`.
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.
Upgrade
Version history
1.0.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources
option-parser — npm install option-parser · libregistry