Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
optionator
Advanced tools
The optionator npm package is used for parsing command-line options. It allows developers to easily define and manage the options their command-line interface (CLI) tools accept. It provides a declarative way to specify the options, their types, default values, and help descriptions. It also automatically generates help text based on the option definitions.
Option Parsing
This code sample demonstrates how to define command-line options and parse them using optionator. It also shows how to display help text if the user passes the 'help' option.
{"const optionator = require('optionator')({ prepend: 'Usage: prog [options]', append: 'Version 1.0.0', options: [{ option: 'help', alias: 'h', type: 'Boolean', description: 'Displays help' },{ option: 'force', alias: 'f', type: 'Boolean', default: 'false', description: 'Force operation' },{ option: 'verbose', type: 'Boolean', default: 'false', description: 'Verbose output' }] }); const options = optionator.parse(process.argv); if (options.help) { console.log(optionator.generateHelp()); process.exit(); }}
Help Text Generation
This code sample shows how to automatically generate and display help text for the defined command-line options.
{"const optionator = require('optionator')({ prepend: 'Usage: prog [options]', append: 'Version 1.0.0', options: [{ option: 'help', alias: 'h', type: 'Boolean', description: 'Displays help' }] }); console.log(optionator.generateHelp());}
Commander is a widely-used npm package for building command-line interfaces. It provides a more object-oriented approach to defining commands and options, and it supports subcommands, which optionator does not. Commander is more feature-rich and has a larger community and ecosystem.
Yargs is another popular npm package for parsing command-line arguments. It offers a fluent interface for building complex CLI tools and supports features like command chaining, context-aware parsing, and automatic help generation. Yargs is more suitable for complex CLI applications compared to optionator.
Minimist is a minimalistic option parsing library. It is simpler and has fewer features than optionator, focusing only on parsing command-line arguments without any automatic help generation or advanced option definitions. It is a good choice for simple use cases where a lightweight solution is preferred.
Optionator is an option parsing and help generation library. It uses type-check and levn behind the scenes to cast and verify input according the specified types. It can accept an array of arguments (like from process.argv
), a string, or an object.
Unlike other libraries, optionator prefers to fail with helpful error messages rather than silently accept poor input.
$ cmd --halp
Invalid option '--halp' - perhaps you meant '--help'?
$ cmd --count str
Invalid value for option 'count' - expected type Int, received value: str.
MIT license. Version 0.1.1.
npm install optionator
For updates on optionator, follow me on twitter.
require('optionator');
returns a function. It has one property, VERSION
, the current version of the library as a string. This function is called with an object specifying your options and other information, see the settings format section. This in turn returns an object with three properties, parse
, generateHelp
, and generateHelpForOption
, which are all functions.
var optionator = require('optionator')({
prepend: 'Usage: cmd [options]',
append: 'Version 1.0.0',
options: [{
option: 'help',
alias: 'h',
type: 'Boolean',
description: 'displays help'
}, {
option: 'count',
alias: 'c',
type: 'Int',
description: 'number of things',
example: 'cmd --count 2'
}]
});
parse
processes the input
according to your settings, and returns an object with the results.
[String] | Object | String
- the input you wish to parse{slice: Int}
- the only current option is slice
, which specifies how much to slice away from the beginning if the input is an array or string - by default 0
for string, 2
for array (works with process.argv
)Object
- the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the _
key.
parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']}
parse('--count 2 positional'); // {count: 2, _: ['positional']}
parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']}
generateHelp
produces help text based on your settings.
{showHidden: Boolean}
- the only current option is showHidden
, which specifies whether to show options with hidden: true
specified, by default it is false
String
- the generated help text
generateHelp(); /*
"Usage: cmd [options] positional
-h, --help displays help
-c, --count Int number of things
Version 1.0.0
"*/
generateHelpForOption
produces expanded help text for the specified with optionName
option. If an example
was specified for the option, it will be displayed, and if a longDescription
was specified, it will display that instead of the description
.
String
- the name of the option to displayString
- the generated help text for the option
generateHelpForOption('count'); /*
"-c, --count Int
description: number of things
example: cmd --count 2
"*/
When your require('optionator')
, you get a function that takes in a settings object. This object has the type:
{
prepend: Maybe String,
append: Maybe String,
options: [{heading: String} | {
option: String,
alias: Maybe [String] | String,
type: Maybe String,
enum: Maybe [String],
default: Maybe String,
restPositional: Maybe Boolean,
requried: Maybe Boolean,
description: Maybe String,
longDescription: Maybe String,
example: Maybe [String] | String
}],
helpStyle: Maybe {
aliasSeparator: Maybe String,
typeSeparator: Maybe String,
descriptionSeparator: Maybe String,
initialIndent: Maybe Int,
secondaryIndent: Maybe Int,
maxPadFactor: Maybe Number
},
mutuallyExclusive: Maybe [[String | [String]]],
}
prepend
is an optional string to be placed before the options in the help textappend
is an optional string to be placed after the options in the help textoptions
is a required array specifying your options and headings, the options and headings will be displayed in the order specifiedhelpStyle
is an optional object which enables you to change the default appearance of some aspects of the help textmutuallyExclusive
is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is presentheading
a required string, the name of the headingoption
the required name of the option - use dash-case, without the leading dashesalias
is an optional string or array of strings which specify any aliases for the optiontype
is a required string in the type check format, this will be used to cast the inputted value and validate itenum
is an optional array of strings, each string will be parsed by levn - the argument value must be one of the resulting values - each potential value must validate against the specified type
default
is a optional string, which will be parsed by levn and used as the default value if none is set - the value must validate against the specified type
restPositional
is an optional boolean - if set to true
, everything after the option will be taken to be a positional argument, even if it looks like a named argumentrequired
is an optional boolean - if set to true
, the option parsing will fail if the option is not defineddescription
is an optional string, which will be displayed next to the option in the help textlongDescription
is an optional string, it will be displayed instead of the description
when generateHelpForOption
is usedexample
is an optional string or array of strings with example(s) for the option - these will be displayed when generateHelpForOption
is usedaliasSeparator
is an optional string, separates multiple names from each other - default: ' ,'typeSeparator
is an optional string, separates the type from the names - default: ' 'descriptionSeparator
is an optional string , separates the description from the padded name and type - default: ' 'initialIndent
is an optional int - the amount of indent for options - default: 2secondaryIndent
is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4maxPadFactor
is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5At the highest level there are two types of arguments: named, and positional.
Name arguments of any length are prefixed with --
(eg. --go
), and those of one character may be prefixed with either --
or -
(eg. -g
).
There are two types of named arguments: boolean flags (eg. --problemo
, -p
) which take no value and result in a true
if they are present, the falsey undefined
if they are not present, or false
if present and explicitly prefixed with no
(eg. --no-problemo
). Named arguments with values (eg. --tseries 800
, -t 800
) are the other type. If the option has a type Boolean
it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value.
For more information about how to properly set types to get the value you want, take a look at the type check and levn pages.
You can group single character arguments that use a single -
, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. -ba 2
is equivalent to -b -a 2
.
Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in cmd -b one -a 2 two
where b
is a boolean flag, and a
has the type Number
, there are two positional arguments, one
and two
.
Everything after an --
is positional, even if it looks like a named argument.
You may optionally use =
to separate option names from values, for example: --count=2
.
If you specify the option NUM
, then any argument using a single -
followed by a number will be valid and will set the value of NUM
. Eg. -2
will be parsed into NUM: 2
.
If duplicate named arguments are present, the last one will be taken.
optionator
is written in LiveScript - a language that compiles to JavaScript. It uses levn to cast arguments to their specified type, and uses type-check to validate values. It also uses the prelude.ls library.
0.1.1
FAQs
option parsing and help generation
The npm package optionator receives a total of 41,150,584 weekly downloads. As such, optionator popularity was classified as popular.
We found that optionator demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.