npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

optist

v3.0.0

Published

Command line option parser

Readme

In a Nutshell

This is a command line option parser that tries not to outsmart the user, but still tries to get the job done.

It has no dependencies and requires Node.js 20 or newer. Run the test suite with npm test.

Example

const Optist = require('optist');

var opt = ((new Optist())
           .simple('a')
           .simple('b')
           .counter('c')
           .simple('d', ['dddddd', 'dddddddd', 'DDD'])
           .string('s', 'string-of-3-chars', /^.{3}$/)
           .multi('m', 'multi-opt')
           .opts([ { shortName: ['A', 'O'], longName: 'all', description: 'It is A and O' },
                   { shortName: 'S', longName: 'required-string', hasArg: true, required: true } ])
           .help('test')
           .parse());

console.log('a', opt.value('a'));
console.log('b', opt.value('b'));
console.log('c', opt.value('c'));
console.log('d', opt.value('d'));
console.log('m', opt.value('m'));
console.log(opt.rest());

Reference

Optist()

Constructor for a command line parser. Does not take arguments. Must be called with new. The class can be extended with class X extends Optist.

All definition methods return the parser itself, so calls can be chained. Definition methods throw an Error if called after parsing, and value methods throw an Error if called before parsing.

Optist.prototype.simple(shortName, longName)

An alias of:

Optist.prototype.o(shortName, longName, false, false, undefined, false, undefined);

This is a simple option that can either be passed once or omitted in the argument list. The value of the option is true if it's present in the argument list, and false otherwise.

Optist.prototype.counter(shortName, longName)

An alias of:

Optist.prototype.o(shortName, longName, false, false, undefined, true, undefined);

This is an option without arguments which can be passed multiple times. The value of the option is the number of times it was present in the argument list.

Optist.prototype.string(shortName, longName, allowedValues)

A simple single-shot option with an optional set of allowed values. Parameter allowedValues can be either a single string or RegExp object or array of strings or RegExp objects or a mixed array of both. If the option is passed, the parsing fails in case the option argument does not match to any of the allowed values.

Without allowedValues parameter, this function is alias of:

Optist.prototype.o(shortName, longName, true, false, undefined, false, undefined);

Optist.prototype.multi(shortName, longName)

An alias of:

Optist.prototype.o(shortName, longName, true, false, undefined, true, undefined);

This is an option with an argument that can be passed multiple times. All passed arguments are collected in an array and are available as a value after the parsing. If the option is not present in the argument list at all, then the value is an empty array.

Optist.prototype.describeOpt(name, description)

Attach a free form text description for an option. This can be done only once for each individual option. The option can be referred to by any of its aliases, short or long. The description is shown in the automatically generated help text.

Optist.prototype.describeParam(num, name, description)

Attach a name and a free form text description for an additional command line parameter. This can be done only once for each individual parameter. Parameters are numbered from 0 up. The name is used in the usage line of the automatically generated help text, when the number of additional parameters is limited with Optist.prototype.additional. If the name is omitted, it defaults to param1, param2 and so on. The description is stored but not yet shown in the help text.

Optist.prototype.attachOptArgCb(name, optArgCb)

Attach an argument processing callback to the previously defined option. The option can be referred to by any of its aliases, short or long. This function can not be called, if optArgCb has already been set for the option. If the option has a default value, it is passed through the callback immediately and must be accepted by it.

Optist.prototype.o(shortName, longName, hasArg, required, defaultValue, multi, optArgCb, requiresAlso, conflictsWith, environment)

A full featured interface for option definition.

shortName

A single character string giving the short name of the option. Can't be a dash (-) or an equal sign (=). Can be an array of multiple short aliases of the same option. Can be omitted if a long name is given.

longName

A multicharacter string giving the long name of the option. Can't be a single character and can't contain an equal sign (=). The first or the last character can't be a dash (-). Can be an array of multiple long aliases of the same option. Can be omitted if a short name is given.

A name that breaks these rules, or is not a string, makes the definition throw an Error. A name can be used only once in a parser, across all options and both short and long aliases.

hasArg

If false, the option does not accept an argument. If true, the argument must be passed.

required

If true, the option must be present (see Option presence below) after the command line and the environment have been processed, otherwise parsing fails. For a required option, it is not possible to give a default value. For an option without an argument, required means that the option must be switched on.

defaultValue

A default value for an option in case it's not present. The default value must always be a string. In case there is an optArgCb for the option, it must be able to process also this default value. A default value can only be set for options accepting an argument.

multi

If true, the option can appear multiple times in the argument list. If the option does not accept an argument, it makes the option a counter, i.e. the value of the option after the parsing, is the number of times the option was present in the command line. If the option accepts the argument, it makes the value of the option after parsing an array containing all arguments given to the option in the order they were given or in case the option is not present at all either an empty array or if there is a default value, then an array containing only the default value.

If not true, the option can only appear once in the argument list.

optArgCb

A processing callback for a command line option argument. This can only be defined for options accepting an argument. The option argument is always passed as a string to the callback and the callback is expected to return the argument in a processed form. The returned value does not have to be a string but can be anything except undefined. If the processing of the argument fails, the callback should return undefined, which triggers an error in command line parsing.

The callback receives the option name as its second parameter: the name as written on the command line (e.g. -s or --str) for command line arguments, and the primary name of the option for default and environment values.

Since this callback is also called for the default value of the option and for a value read from the environment, side effects are not desirable.

Pre-made callbacks are available in the util module of the optist package.

requiresAlso

A single string or array of strings listing options that must also be present if this option is present. The check is one-directional: the listed options can be present without this option.

conflictsWith

A single string or array of strings listing options that must not be present if this option is present.

environment

If the option is not given on the command line, read its value from the environment variable with the given name. The environment is read when parse is called. A value from the environment overrides the default value, is passed through optArgCb, satisfies required and makes the option present.

For an option with an argument, any string, including an empty one, is a valid value. For a multi option the whole variable becomes the single element of the value array.

For an option without an argument, the allowed values are yes and no (with aliases true/false and +/- respectively, case insensitive). A counter option additionally accepts a non-negative integer. Any other value, including an empty string, is a parsing error.

Optist.prototype.opts(options)

A shortcut method to define multiple options. Parameter options is an option definition object or an array of them. Each option definition is an object with properties from list: shortName, longName, hasArg, required, defaultValue, multi, optArgCb, requiresAlso, conflictsWith, environment, description. See Optist.prototype.o() for definition of each property; description is passed to Optist.prototype.describeOpt().

Optist.prototype.additional(restRequireMin, restRequireMax)

Set the minimum and/or maximum number of additional parameters that must be left in the argument list after the options have been parsed. This can be done only before parsing and can be set only once. Alternatively the limits can be set also with additional function arguments for parse/parsePosix methods, but it is recommended to use Optist.prototype.additional API instead, because the information is used in the usage line of the help text.

Optist.prototype.help(command)

Enable the automatic help message generation and attach it to command line options -h and --help. Those options must not be otherwise attached. When -h or --help is encountered in the argument list, the help message is printed to the standard output and the program terminates with exit code 0. In case of a parsing error of command line options, an error message followed by the help message is printed to the standard error and the program terminates with exit code 1. Without this call, parsing errors throw an Error instead. This function can only be called before parsing.

If parameter command is given, the program name is overridden in the help messages. Command defaults to the base names of process.argv[0] and process.argv[1] separated by a space, e.g. node script.js.

The generated help message consists of a Usage: line and the option list. It can be replaced with Optist.prototype.helpMessage() and framed with Optist.prototype.helpMessageHead() and Optist.prototype.helpMessageTail().

Optist.prototype.helpMessage(message)

Replace the generated help message, including its Usage: line, with message. The string is printed as is, so it may contain several lines and should not end with a line break. An empty string is accepted and removes the generated help message, so that only the head and the tail, if set, are printed. The message must be a string, can be set only once and can only be set before parsing. It does not change the return value of Optist.prototype.generateHelp().

Optist.prototype.helpMessageHead(text)

Prepend text to the help message, whether it is the generated one or one set with Optist.prototype.helpMessage(). A line break separates text from the help message, so end text with a line break only if an empty line is wanted in between. An empty string adds nothing. Text must be a string, can be set only once and can only be set before parsing.

Optist.prototype.helpMessageTail(text)

Append text to the help message, whether it is the generated one or one set with Optist.prototype.helpMessage(). A line break separates the help message from text, so start text with a line break only if an empty line is wanted in between. An empty string adds nothing. Text must be a string, can be set only once and can only be set before parsing.

The head and the tail are printed wherever the help message is: for -h and --help, after the error line of a parsing error, and by Optist.prototype.showHelpAndExit() and Optist.prototype.showErrorMessageHelpAndExitIfHelpEnabled(). The order of these calls and Optist.prototype.help() does not matter.

(new Optist())
  .simple('v', 'verbose')
  .describeOpt('verbose', 'Print more')
  .help('mycmd')
  .helpMessageHead('mycmd copies things around.')
  .helpMessageTail('Examples:\n  mycmd -v src dst')
  .parse();

prints for --help:

mycmd copies things around.
Usage:
  mycmd [<opt> ...] [<param> ...]
Options:
  -v  --verbose  Print more
  -h  --help     Show help and exit
Examples:
  mycmd -v src dst

Optist.prototype.parse(av, restRequireMin, restRequireMax)

Parse the argument list. The parsing stops when the first non-option argument is detected or when the parsing is explicitly stopped by two dashes '--' in the argument list. This is the sane way. The rest of the argument list can be retrieved using Optist.prototype.rest() interface. The parameters restRequireMin and restRequireMax can be used in order to set constraints for the number of arguments that must be left in the argument list, after the parsing has completed.

If the argument list av is omitted or set to undefined, it defaults to process.argv.slice(2). The array that is passed is consumed during parsing, so pass a copy if you need it afterwards.

Supported argument styles are -a, -abc for several options without arguments, -o value, --opt value and --opt=value. A single dash - is a non-option argument. An option argument may start with a dash. The styles -ovalue and -o=value are not supported.

After the argument list, the environment, required options, requiresAlso and conflictsWith are checked, in that order, and finally the number of additional parameters.

Optist.prototype.parsePosix(av, restRequireMin, restRequireMax)

Parse the argument list in weird but kinda Posixly standard way. The parsing stops, if it's explicitly stopped by two dashes '--' in the argument list. Otherwise, non-option arguments are skipped and the parsing resumed until entire argument list has been processed. Whatever was skipped on the way, can be retrieved using Optist.prototype.rest() interface. In my opinion, this is totally bonkers, but in case this is how you like it, so be it. Otherwise this interface acts like Optist.prototype.parse().

Optist.prototype.rest()

Return whatever is left of the argument list after the options have been parsed and removed. This function always returns a new array, so the caller modifying the array is ok. This function can be called multiple times and a new array is returned each time.

Optist.prototype.value(name)

Lookup the value of an option after parsing the command line. The name of the option can be given either as a long or short option name. If the option has multiple aliases, all names return the same value. An unknown name returns undefined.

The value is true or false for an option without an argument, a non-negative integer for a counter, the processed argument, the default value or undefined for an option with an argument, and for a multi option a new array of processed arguments, or an array with only the default value, or an empty array.

Optist.prototype.values()

Return all option values after parsing the command line. Return value is an object with all aliases of the options as properties and a corresponding option value as a value of each property. Options that have no value given in the command line or does not have a default value, are omitted. The exception is a multi type options that are either [] or 0 depending on whether they accept an argument or not.

In addition, the non-option argument list (as returned with Optist.prototype.rest()) is stored to the object with property name consisting of a single dash (i.e. '-').

Optist.prototype.forEach(cb)

Iterate over the defined options after parsing and call a caller provided callback for each option in the definition order. Parameters passed to the callback are primary short option name, primary long option name and option value. If option was not given on the command line and has no default value, the value is then passed as undefined. Also if the short or long option name does not exist, it is passed as undefined.

opt.forEach(function(s, l, v) {
  console.log('short:', s, 'long:', l, 'value:', v);
});

Optist.prototype.some(cb)

Like Optist.prototype.forEach(), but stops at the first option for which the callback returns a true value and returns true. If the callback never returns a true value, returns false.

Optist.prototype.generateHelp(command)

Return the generated help text as a string without printing it. The Usage: heading and the texts set with Optist.prototype.helpMessage(), Optist.prototype.helpMessageHead() and Optist.prototype.helpMessageTail() are not included. Parameter command is handled as in Optist.prototype.help(). This can be called before and after parsing and does not require help to be enabled.

Optist.prototype.showHelpAndExit(exitValue)

Print the help message to the standard output and exit the process with exitValue. This is what -h and --help do. The help message is composed as described in Optist.prototype.help() and the help message methods, and this works also when automatic help is not enabled.

Optist.prototype.showErrorMessageHelpAndExitIfHelpEnabled(message, exitValue)

If automatic help is enabled with Optist.prototype.help(), print the message prefixed with Error: , followed by the help message, to the standard error and exit the process with exitValue. If automatic help is not enabled, do nothing and return the parser. This is what parsing errors do, and the method can be used by the program for its own validation errors after parsing, so that they are reported the same way. An empty message prints only the help message.

Option presence

Several checks depend on whether an option is present. An option is present when it was given on the command line or through its environment variable. In detail:

  • An option without an argument is present when its value is true.
  • A counter is present when its count is greater than zero.
  • An option with an argument is present when it has a value.
  • A multi option is present when it has at least one value.

A default value does not make an option present. A value read from the environment does.

The required check fails if a required option is not present. The requiresAlso check fails if an option is present and one of the listed options is not. The conflictsWith check fails if an option is present and one of the listed options is present too.

Utilities

Some generic argument callbacks are provided by util library. Those functions can be passed as optArgCb in option definition. User can of course also define custom callbacks. Every callback returns undefined for an argument it does not accept.

const Optist = require('optist');
const ou = require('optist/util');

var opt = ((new Optist())
           .o(undefined, 'integer-option', true, false, '42', false, ou.integerCb)
           .parse())
console.log('integer option:',
            opt.value('integer-option'),
            'of type',
            typeof(opt.value('integer-option')));

nonEmptyCb(s)

Accepts any non-empty string as is.

integerCb(s)

Accepts a decimal integer in canonical form (no leading zeros, no plus sign, no -0) within the safe integer range and returns it as a number.

integerListCb(s)

Accepts a comma separated list of integers as integerCb does, with optional whitespace around the commas and the list, and returns an array of numbers. An empty list is not accepted.

integerWithLimitsCbFactory(min, max)

Returns a callback that accepts an integer as integerCb does, within the inclusive limits. Either limit can be undefined.

allowListCbFactory(allowedValues)

Returns a callback that accepts a string that equals one of the allowed strings or matches one of the allowed RegExp objects. Parameter allowedValues is a single string or RegExp or an array of them. Any other entry makes the factory throw an Error.

existingFileNameCb(s)

Accepts the name of an existing regular file as is.

fileContentsStringCb(s)

Accepts the name of an existing regular file and returns its contents as a utf8 string, which may be empty.

ipv4(s)

Accepts a dotted quad IPv4 address with octets in canonical decimal form and returns it as a string.

jsonObject(s)

Accepts a JSON text whose value is an object (not an array or null) and returns the parsed object.

jsonArray(s)

Accepts a JSON text whose value is an array and returns the parsed array.

Changes

See CHANGELOG.md. Version 3.0.0 changes behaviour in a few places, most importantly requiresAlso, conflictsWith and required for options without an argument and for multi options, the output stream of error messages, and the enforcement of option name rules.

Author

Timo J. Rinne [email protected]

License

MIT License