or run

npx @tessl/cli init
Log in

Version

Files

tile.json

tessl/npm-optimist

Light-weight option parsing with an argv hash for Node.js command-line applications

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/optimist@0.6.x

To install, run

npx @tessl/cli install tessl/npm-optimist@0.6.0

index.mddocs/

Optimist

Optimist is a lightweight command-line argument parsing library for Node.js applications. It provides an intuitive API for parsing process.argv with support for short and long options, boolean flags, default values, aliases, and automatic help generation, making it easy to create command-line interfaces without complex configuration.

Package Information

  • Package Name: optimist
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install optimist

Core Imports

var optimist = require('optimist');
var argv = optimist.argv;

Direct argv access:

var argv = require('optimist').argv;

Basic Usage

#!/usr/bin/env node
var argv = require('optimist').argv;

if (argv.rif - 5 * argv.xup > 7.138) {
    console.log('Buy more riffiwobbles');
}
else {
    console.log('Sell the xupptumblers');
}

More comprehensive example with configuration:

var optimist = require('optimist');

var argv = optimist
    .usage('Usage: $0 -f [file] -p [port]')
    .demand(['f'])
    .alias('f', 'file')
    .alias('p', 'port')
    .default('p', 3000)
    .describe('f', 'Input file path')
    .describe('p', 'Server port number')
    .boolean('verbose')
    .argv;

console.log('File:', argv.file);
console.log('Port:', argv.port);
console.log('Verbose:', argv.verbose);

Architecture

Optimist uses a simple architecture centered around:

  • Main Instance: Pre-configured parser instance with bound methods
  • Method Chaining: Fluent API where configuration methods return the instance
  • Lazy Parsing: Arguments are parsed when .argv property is accessed
  • Configuration State: Internal state tracks options, defaults, aliases, and validation rules

Capabilities

Core Argument Parsing

The fundamental parsed arguments object containing all command-line parameters.

/**
 * Parsed command-line arguments object with proper keys set
 * @type {Object}
 */
argv

Custom Argument Parsing

Parse a specific arguments array instead of process.argv.

/**
 * Parse provided args array instead of process.argv
 * @param {Array} args - Arguments array to parse
 * @returns {Object} Parsed arguments object
 */
.parse(args)

Usage Example:

var optimist = require('optimist');
var args = ['--verbose', '--file', 'input.txt', '--port', '8080'];
var parsed = optimist.parse(args);
console.log(parsed); // { verbose: true, file: 'input.txt', port: 8080, _: [] }

Option Configuration

Configure individual options with detailed specifications.

/**
 * Set a key with options configuration
 * @param {string} key - Option key name
 * @param {Object} opt - Option configuration object
 * @returns {Object} Optimist instance for chaining
 */
.option(key, opt)

Usage Example:

var argv = require('optimist')
    .option('f', {
        alias: 'file',
        demand: true,
        default: 'input.txt',
        describe: 'Input file path',
        type: 'string'
    })
    .argv;

Usage Message Configuration

Set a usage message for help output display.

/**
 * Set a usage message for help output
 * @param {string} message - Usage message text
 * @returns {Object} Optimist instance for chaining
 */
.usage(message)

Usage Example:

var argv = require('optimist')
    .usage('Usage: $0 [options]')
    .usage('Process files with various options')
    .argv;

Required Arguments

Demand that particular keys exist in the parsed arguments.

/**
 * Demand that particular keys exist in arguments
 * @param {string|Array} key - Required key name(s)
 * @returns {Object} Optimist instance for chaining
 */
.demand(key)

Usage Example:

var argv = require('optimist')
    .demand(['input', 'output'])
    .demand('config')
    .argv;
// Will exit with error if input, output, or config are not provided

Default Values

Set default values for command-line options.

/**
 * Set default values for particular keys
 * @param {string} key - Option key name
 * @param {*} value - Default value (any type)
 * @returns {Object} Optimist instance for chaining
 */
.default(key, value)

Usage Example:

var argv = require('optimist')
    .default('port', 3000)
    .default('host', 'localhost')
    .default('verbose', false)
    .argv;

Boolean Type Interpretation

Interpret specified keys as boolean values.

/**
 * Interpret a key as a boolean value
 * @param {string|Array} key - Key name(s) to treat as boolean
 * @returns {Object} Optimist instance for chaining
 */
.boolean(key)

Usage Example:

var argv = require('optimist')
    .boolean(['verbose', 'debug', 'force'])
    .argv;
// --verbose becomes true, --no-verbose becomes false

String Type Interpretation

Force specified keys to be interpreted as strings, preventing numeric coercion.

/**
 * Tell parser not to interpret key as number or boolean
 * @param {string|Array} key - Key name(s) to treat as string
 * @returns {Object} Optimist instance for chaining
 */
.string(key)

Usage Example:

var argv = require('optimist')
    .string(['id', 'version'])
    .argv;
// --id 001 remains "001" instead of becoming 1

Help Text Formatting

Configure text wrapping for help output display.

/**
 * Format usage output to wrap at specified columns
 * @param {number} columns - Number of columns for text wrapping
 * @returns {Object} Optimist instance for chaining
 */
.wrap(columns)

Usage Example:

var optimist = require('optimist')
    .wrap(80)
    .describe('very-long-option-name', 'This is a very long description that will be wrapped at 80 columns for better readability in terminal output');

Help Text Generation

Generate formatted help text string.

/**
 * Return the generated usage string
 * @returns {string} Formatted help text
 */
.help()

Usage Example:

var optimist = require('optimist')
    .usage('Usage: $0 [options]')
    .describe('input', 'Input file path')
    .describe('output', 'Output file path');

console.log(optimist.help());

Help Text Display

Print usage information using a specified output function.

/**
 * Print usage data using specified function
 * @param {Function} [fn=console.error] - Function for printing help text
 * @returns {Object} Optimist instance for chaining
 */
.showHelp(fn)

Usage Example:

var optimist = require('optimist')
    .usage('Usage: $0 [options]')
    .describe('help', 'Show help information');

if (argv.help) {
    optimist.showHelp(console.log); // Use console.log instead of console.error
    process.exit(0);
}

Option Aliases

Create alternative names for command-line options.

/**
 * Set an alias for a key
 * @param {string} key - Original key name
 * @param {string} alias - Alias name
 * @returns {Object} Optimist instance for chaining
 */
.alias(key, alias)

Usage Example:

var argv = require('optimist')
    .alias('f', 'file')
    .alias('p', 'port')
    .alias('v', 'verbose')
    .argv;
// Both -f and --file will set the 'file' property

Option Descriptions

Add descriptive text for options in help output.

/**
 * Describe a key for generated usage information
 * @param {string} key - Option key name
 * @param {string} desc - Description text
 * @returns {Object} Optimist instance for chaining
 */
.describe(key, desc)

Usage Example:

var argv = require('optimist')
    .describe('input', 'Path to the input file')
    .describe('output', 'Path to the output file')
    .describe('verbose', 'Enable verbose logging')
    .argv;

Custom Validation

Implement custom validation logic for parsed arguments.

/**
 * Check that certain conditions are met in provided arguments
 * @param {Function} fn - Validation function that throws on failure
 * @returns {Object} Optimist instance for chaining
 */
.check(fn)

Usage Example:

var argv = require('optimist')
    .check(function(argv) {
        if (argv._.length === 0) {
            throw new Error('At least one input file is required');
        }
        if (argv.port && (argv.port < 1 || argv.port > 65535)) {
            throw new Error('Port must be between 1 and 65535');
        }
    })
    .argv;

Common Patterns

Configuration-Heavy CLI Tools

var optimist = require('optimist');

var argv = optimist
    .usage('Usage: $0 [options]')
    .option('config', {
        alias: 'c',
        describe: 'Configuration file path',
        type: 'string'
    })
    .option('verbose', {
        alias: 'v',
        describe: 'Enable verbose output',
        type: 'boolean',
        default: false
    })
    .option('port', {
        alias: 'p',
        describe: 'Server port',
        type: 'number',
        default: 3000
    })
    .demand(['config'])
    .check(function(argv) {
        if (!require('fs').existsSync(argv.config)) {
            throw new Error('Configuration file does not exist: ' + argv.config);
        }
    })
    .argv;

Simple Utility Scripts

var argv = require('optimist')
    .boolean('dry-run')
    .default('format', 'json')
    .string(['input', 'output'])
    .argv;

if (argv['dry-run']) {
    console.log('Dry run mode - no changes will be made');
}

Error Handling

Optimist will automatically exit the process with an error message when:

  • Required arguments (via .demand()) are missing
  • Custom validation (via .check()) fails
  • Invalid usage patterns are detected

To handle errors gracefully in your application, wrap optimist usage in try-catch blocks or use .parse() instead of .argv for more control over error handling.