Command-line Option Parser
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.
Common errors
-
ReferenceError: OptionParser is not defined
cause The `OptionParser` class was not correctly imported or required before use.fixEnsure `const OptionParser = require('option-parser');` is at the top of your file before instantiating the parser. -
TypeError: parser.addOption is not a function
cause `addOption` is a method of an `OptionParser` instance, but it's being called on an undefined or incorrect object.fixVerify 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.
cause Options are case-sensitive, or an expected option alias/format was not registered with `addOption`.fixDouble-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.
Warnings
- gotcha 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.
- gotcha 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.
- gotcha 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.
Install
-
npm install option-parser -
yarn add option-parser -
pnpm add option-parser
Imports
- OptionParser
import { OptionParser } from 'option-parser';const OptionParser = require('option-parser'); - parser.addOption
parser.addOption('h', 'help', 'Display help') - parser.parse
const unparsedArgs = parser.parse();
Quickstart
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;
}