Command-line Option Parser

1.0.2 · maintenance · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

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;
}

view raw JSON →