Light-weight option parsing with an argv hash for Node.js command-line applications
npx @tessl/cli install tessl/npm-optimist@0.6.0Optimist 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.
npm install optimistvar optimist = require('optimist');
var argv = optimist.argv;Direct argv access:
var argv = require('optimist').argv;#!/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);Optimist uses a simple architecture centered around:
.argv property is accessedThe fundamental parsed arguments object containing all command-line parameters.
/**
* Parsed command-line arguments object with proper keys set
* @type {Object}
*/
argvParse 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, _: [] }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;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;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 providedSet 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;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 falseForce 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 1Configure 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');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());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);
}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' propertyAdd 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;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;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;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');
}Optimist will automatically exit the process with an error message when:
.demand()) are missing.check()) failsTo 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.