function Yargs(processArgs, cwd, parentRequire) {
processArgs = processArgs || [] // handle calling yargs().
const self = {}
var command = null
var completion = null
var groups = {}
var output = ''
var preservedGroups = {}
var usage = null
var validation = null
const y18n = Y18n({
directory: path.resolve(__dirname, './locales'),
updateFiles: false
})
if (!cwd) cwd = process.cwd()
self.$0 = process.argv
.slice(0, 2)
.map(function (x, i) {
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
if (i === 0 && /\b(node|iojs)(\.exe)?$/.test(x)) return
var b = rebase(cwd, x)
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x
})
.join(' ').trim()
if (process.env._ !== undefined && process.argv[1] === process.env._) {
self.$0 = process.env._.replace(
path.dirname(process.execPath) + '/', ''
)
}
// use context object to keep track of resets, subcommand execution, etc
// submodules should modify and check the state of context as necessary
const context = { resets: -1, commands: [], files: [] }
self.getContext = function () {
return context
}
// puts yargs back into an initial state. any keys
// that have been set to "global" will not be reset
// by this action.
var options
self.resetOptions = self.reset = function (aliases) {
context.resets++
aliases = aliases || {}
options = options || {}
// put yargs back into an initial state, this
// logic is used to build a nested command
// hierarchy.
var tmpOptions = {}
tmpOptions.local = options.local ? options.local : []
tmpOptions.configObjects = options.configObjects ? options.configObjects : []
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
var localLookup = {}
tmpOptions.local.forEach(function (l) {
localLookup[l] = true
;(aliases[l] || []).forEach(function (a) {
localLookup[a] = true
})
})
// preserve all groups not set to local.
preservedGroups = Object.keys(groups).reduce(function (acc, groupName) {
var keys = groups[groupName].filter(function (key) {
return !(key in localLookup)
})
if (keys.length > 0) {
acc[groupName] = keys
}
return acc
}, {})
// groups can now be reset
groups = {}
var arrayOptions = [
'array', 'boolean', 'string', 'requiresArg', 'skipValidation',
'count', 'normalize', 'number'
]
var objectOptions = [
'narg', 'key', 'alias', 'default', 'defaultDescription',
'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce'
]
arrayOptions.forEach(function (k) {
tmpOptions[k] = (options[k] || []).filter(function (k) {
return !localLookup[k]
})
})
objectOptions.forEach(function (k) {
tmpOptions[k] = objFilter(options[k], function (k, v) {
return !localLookup[k]
})
})
tmpOptions.envPrefix = options.envPrefix
options = tmpOptions
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
usage = usage ? usage.reset(localLookup) : Usage(self, y18n)
validation = validation ? validation.reset(localLookup) : Validation(self, usage, y18n)
command = command ? command.reset() : Command(self, usage, validation)
if (!completion) completion = Completion(self, usage, command)
if (!strictGlobal) strict = false
completionCommand = null
output = ''
exitError = null
hasOutput = false
self.parsed = false
return self
}
self.resetOptions()
// temporary hack: allow "freezing" of reset-able state for parse(msg, cb)
var frozen
function freeze () {
frozen = {}
frozen.options = options
frozen.configObjects = options.configObjects.slice(0)
frozen.exitProcess = exitProcess
frozen.groups = groups
usage.freeze()
validation.freeze()
command.freeze()
frozen.strict ...n/a
_getLoggerInstance = function () { [native code] }...
failMessage = message
showHelpOnFail = enabled
return self
}
var failureOutput = false
self.fail = function (msg, err) {
const logger = yargs._getLoggerInstance()
if (fails.length) {
for (var i = fails.length - 1; i >= 0; --i) {
fails[i](msg, err, self)
}
} else {
if (yargs.getExitProcess()) setBlocking(true)
..._getParseContext = function () { [native code] }...
})
Object.keys(argv).forEach(function (key) {
if (key !== '$0' && key !== '_' &&
!descriptions.hasOwnProperty(key) &&
!demandedOptions.hasOwnProperty(key) &&
!positionalMap.hasOwnProperty(key) &&
!yargs._getParseContext().hasOwnProperty(key) &&
!aliasLookup.hasOwnProperty(key)) {
unknown.push(key)
}
})
if (commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach(function (key) {
..._hasOutput = function () { [native code] }...
Object.keys(commandHandler.builder).forEach(function (key) {
innerYargs.option(key, commandHandler.builder[key])
})
innerArgv = innerYargs._parseArgs(null, null, true)
aliases = innerYargs.parsed.aliases
}
if (!yargs._hasOutput()) {
positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs)
}
// we apply validation post-hoc, so that custom
// checks get passed populated positional arguments.
if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error)
..._hasParseCallback = function () { [native code] }...
// we use a custom logger that buffers output,
// so that we can print to non-CLIs, e.g., chat-bots.
var _logger = {
log: function () {
const args = []
for (var i = 0; i < arguments.length; i++) args.push(arguments[i])
if (!self._hasParseCallback()) console.log.apply(console, args)
hasOutput = true
if (output.length) output += '\n'
output += args.join(' ')
},
error: function () {
const args = []
for (var i = 0; i < arguments.length; i++) args.push(arguments[i])
..._parseArgs = function () { [native code] }...
// completion short-circuits the parsing process,
// skipping validation, etc.
if (!shortCircuit) processArgs = args
freeze()
if (parseFn) exitProcess = false
var parsed = self._parseArgs(args, shortCircuit)
if (parseFn) parseFn(exitError, parsed, output)
unfreeze()
return parsed
}
self._getParseContext = function () {
..._runValidation = function () { [native code] }...
// or if explicitly skipped, we won't run validations.
if (!skipValidation) {
if (parsed.error) throw new YError(parsed.error.message)
// if we're executed via bash completion, don't
// bother with validation.
if (!argv[completion.completionKey]) {
self._runValidation(argv, aliases, {}, parsed.error)
}
}
} catch (err) {
if (err instanceof YError) usage.fail(err.message, err)
else throw err
}
..._setHasOutput = function () { [native code] }...
}
// we apply validation post-hoc, so that custom
// checks get passed populated positional arguments.
if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error)
if (commandHandler.handler && !yargs._hasOutput()) {
yargs._setHasOutput()
commandHandler.handler(innerArgv)
}
if (command) currentContext.commands.pop()
numFiles = currentContext.files.length - numFiles
if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)
...addHelpOpt = function () { [native code] }n/a
alias = function () { [native code] }...
count.js:
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.count('verbose')
.alias('v', 'verbose')
.argv;
VERBOSE_LEVEL = argv.verbose;
function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); }
function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); }
function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); }
...array = function () { [native code] }...
works in bash or perl.
If `yargs` is executed in an environment that embeds node and there's no script name (e.g.
[Electron](http://electron.atom.io/) or [nw.js](http://nwjs.io/)), it will ignore the first parameter since it
expects it to be the script name. In order to override this behavior, use `.parse(process.argv.slice(1))`
instead of `.argv` and the first parameter won't be ignored.
<a name="array"></a>.array(key)
----------
Tell the parser to interpret `key` as an array. If `.array('foo')` is set,
`--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`.
<a name="boolean"></a>.boolean(key)
-------------
...boolean = function () { [native code] }...
---------------------------------------------------------
boolean_single.js:
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.boolean('v')
.argv
;
console.dir(argv.v);
console.dir(argv._);
````
***
...check = function () { [native code] }...
`process.argv`, that string won't get set as the value of `key`.
`key` will default to `false`, unless a `default(key, undefined)` is
explicitly set.
If `key` is an array, interpret all the elements as booleans.
.check(fn, [global=true])
----------
Check that certain conditions are met in the provided arguments.
`fn` is called with two arguments, the parsed `argv` hash and an array of options and their aliases.
If `fn` throws or returns a non-truthy value, show the thrown error, usage information, and
...choices = function () { [native code] }...
If `fn` throws or returns a non-truthy value, show the thrown error, usage information, and
exit.
`global` indicates whether `check()` should be enabled both
at the top-level and for each sub-command.
<a name="choices"></a>.choices(key, choices)
----------------------
Limit valid values for `key` to a predefined set of `choices`, given as an array
or as an individual value.
```js
var argv = require('yargs')
...coerce = function () { [native code] }...
alias: 's',
describe: 'choose a size',
choices: ['xs', 's', 'm', 'l', 'xl']
})
.argv
```
<a name="coerce"></a>.coerce(key, fn)
----------------
Provide a synchronous function to coerce or transform the value(s) given on the
command line for `key`.
The coercion function should accept one argument, representing the parsed value
from the command line, and should return a new value or throw an error. The
...command = function () { [native code] }...
line_count.js:
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.usage('Usage: $0 <command> [options]')
.command('count', 'Count the lines in a file')
.example('$0 count -f foo.js', 'count the lines in the given file')
.alias('f', 'file')
.nargs('f', 1)
.describe('f', 'Load a file')
.demandOption(['f'])
.help('h')
.alias('h', 'help')
...commandDir = function () { [native code] }...
```js
yargs.command('get <source> [proxy]', 'make a get HTTP request', require('my-module'))
.help()
.argv
```
.commandDir(directory, [opts])
------------------------------
Apply command modules from a directory relative to the module calling this method.
This allows you to organize multiple commands into their own modules under a
single directory and apply all of them at once instead of calling
`.command(require('./dir/module'))` multiple times.
...completion = function () { [native code] }...
exports.desc = 'Delete tracked branches gone stale for remotes'
exports.builder = {}
exports.handler = function (argv) {
console.log('pruning remotes %s', [].concat(argv.name).concat(argv.names).join(', '))
}
```
.completion([cmd], [description], [fn])
---------------------------------------
Enable bash-completion shortcuts for commands and options.
`cmd`: When present in `argv._`, will result in the `.bashrc` completion script
being outputted. To enable bash completions, concat the generated script to your
`.bashrc` or `.bash_profile`.
...config = function () { [native code] }...
resolve(['apple', 'banana'])
}, 10)
})
})
.argv;
```
<a name="config"></a>.config([key], [description], [parseFn
])
-------------------------------------------------------------
.config(object)
---------------
Tells the parser that if the option specified by `key` is passed in, it
should be interpreted as a path to a JSON config file. The file is loaded
and parsed, and its properties are set as arguments. Because the file is
...conflicts = function () { [native code] }...
foo: 1,
bar: 2,
'$0': 'test.js' }
```
Note that a configuration object may extend from a JSON file using the `"extends"` property. When doing so, the `"
;extends"` value should be a path (relative or absolute) to the extended JSON file.
<a name="conflicts"></a>.conflicts(x, y)
----------------------------------------------
Given the key `x` is set, the key `y` must not be set.
Optionally `.conflicts()` can accept an object specifying multiple conflicting keys.
<a name="count"></a>.count(key)
...count = function () { [native code] }...
----------------------------------------------------------------------
count.js:
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.count('verbose')
.alias('v', 'verbose')
.argv;
VERBOSE_LEVEL = argv.verbose;
function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); }
function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); }
...default = function () { [native code] }...
------------------
default_singles.js:
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.default('x', 10)
.default('y', 10)
.argv
;
console.log(argv.x + argv.y);
````
***
...defaults = function () { [native code] }...
------------
Interpret `key` as a boolean flag, but set its parsed value to the number of
flag occurrences rather than `true` or `false`. Default value is thus `0`.
<a name="default"></a>.default(key, value, [description])
---------------------------------------------------------
.defaults(key, value, [description])
------------------------------------
**Note:** The `.defaults()` alias is deprecated. It will be
removed in the next major version.
Set `argv[key]` to `value` if no option was specified in `process.argv`.
...demand = function () { [native code] }...
Optionally, `description` can also be provided and will take precedence over
displaying the value in the usage instructions:
```js
.default('timeout', 60000, '(one-minute)')
```
<a name="demand"></a>.demand(count, [max], [msg]) [DEPRECATED
]
--------------------
`demand()` has been deprecated, please instead see [`demandOption()`](#demandOption) and
[`demandCommand()`](#demandCommand).
<a name="demandOption"></a>.demandOption(key, [msg | boolean])
------------------------------
...demandCommand = function () { [native code] }...
-----------------------------------------
demand_count.js:
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.demandCommand(2)
.argv;
console.dir(argv);
````
***
$ ./demand_count.js a
...demandOption = function () { [native code] }...
area.js:
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.usage('Usage: $0 -w [num] -h [num]')
.demandOption(['w','h'])
.argv;
console.log("The area is:", argv.w * argv.h);
````
***
...describe = function () { [native code] }...
#!/usr/bin/env node
var argv = require('yargs')
.usage('Usage: $0 <command> [options]')
.command('count', 'Count the lines in a file')
.example('$0 count -f foo.js', 'count the lines in the given file')
.alias('f', 'file')
.nargs('f', 1)
.describe('f', 'Load a file')
.demandOption(['f'])
.help('h')
.alias('h', 'help')
.epilog('copyright 2015')
.argv;
var fs = require('fs');
...detectLocale = function () { [native code] }...
<a name="describe"></a>.describe(key, desc)
--------------------
Describe a `key` for the generated usage information.
Optionally `.describe()` can take an object that maps keys to descriptions.
.detectLocale(boolean)
-----------
Should yargs attempt to detect the os' locale? Defaults to `true`.
.env([prefix])
--------------
...env = function () { [native code] }...
Optionally `.describe()` can take an object that maps keys to descriptions.
.detectLocale(boolean)
-----------
Should yargs attempt to detect the os' locale? Defaults to `true`.
.env([prefix])
--------------
Tell yargs to parse environment variables matching the given prefix and apply
them to argv as though they were command line arguments.
Use the "__" separator in the environment variable to indicate nested options.
(e.g. prefix_nested__foo => nested.foo)
...epilog = function () { [native code] }...
.example('$0 count -f foo.js', 'count the lines in the given file')
.alias('f', 'file')
.nargs('f', 1)
.describe('f', 'Load a file')
.demandOption(['f'])
.help('h')
.alias('h', 'help')
.epilog('copyright 2015')
.argv;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
var lines = 0;
s.on('data', function (buf) {
...epilogue = function () { [native code] }...
```
Env var parsing is disabled by default, but you can also explicitly disable it
by calling `.env(false)`, e.g. if you need to undo previous configuration.
.epilog(str)
------------
.epilogue(str)
--------------
A message to print at the end of the usage instructions, e.g.
```js
var argv = require('yargs')
.epilogue('for more information, find our manual at http://example.com');
...example = function () { [native code] }...
line_count.js:
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.usage('Usage: $0 <command> [options]')
.command('count', 'Count the lines in a file')
.example('$0 count -f foo.js', 'count the lines in the given file'
;)
.alias('f', 'file')
.nargs('f', 1)
.describe('f', 'Load a file')
.demandOption(['f'])
.help('h')
.alias('h', 'help')
.epilog('copyright 2015')
...exit = function () { [native code] }...
```js
var argv = require('yargs')
.fail(function (msg, err, yargs) {
if (err) throw err // preserve stack
console.error('You broke it!')
console.error(msg)
console.error('You should be doing', yargs.help())
process.exit(1)
})
.argv
```
.getCompletion(args, done);
---------------------------
...exitProcess = function () { [native code] }...
-------------------
Give some example invocations of your program. Inside `cmd`, the string
`$0` will get interpolated to the current script name or node command for the
present script similar to how `$0` works in bash or perl.
Examples will be printed out as part of the help message.
<a name="exitprocess"></a>.exitProcess(enable)
----------------------------------
By default, yargs exits the process when the user passes a help flag, uses the
`.version` functionality, or when validation fails. Calling
`.exitProcess(false)` disables this behavior, enabling further actions after
yargs have been validated.
...fail = function () { [native code] }...
The coercion function should accept one argument, representing the parsed value
from the command line, and should return a new value or throw an error. The
returned value will be used as the value for `key` (or one of its aliases) in
`argv`.
If the function throws, the error will be treated as a validation
failure, delegating to either a custom [`.fail()`](#fail) handler or printing
the error message in the console.
Coercion will be applied to a value after
all other modifications, such as [`.normalize()`](#normalize).
_Examples:_
...getCommandInstance = function () { [native code] }...
}
// check for unknown arguments (strict-mode).
self.unknownArguments = function (argv, aliases, positionalMap) {
const aliasLookup = {}
const descriptions = usage.getDescriptions()
const demandedOptions = yargs.getDemandedOptions()
const commandKeys = yargs.getCommandInstance().getCommands()
const unknown = []
const currentContext = yargs.getContext()
Object.keys(aliases).forEach(function (key) {
aliases[key].forEach(function (alias) {
aliasLookup[alias] = key
})
...getCompletion = function () { [native code] }...
console.error(msg)
console.error('You should be doing', yargs.help())
process.exit(1)
})
.argv
```
.getCompletion(args, done);
---------------------------
Allows to programmatically get completion choices for any line.
`args`: An array of the words in the command line to complete.
`done`: The callback to be called with the resulting completions.
...getContext = function () { [native code] }...
command.addHandler(cmd, description, builder, handler)
return self
}
self.commandDir = function (dir, opts) {
argsert('<string> [object]', [dir, opts], arguments.length)
const req = parentRequire || require
command.addDirectory(dir, self.getContext(), req, require('get-caller-file'
;)(), opts)
return self
}
// TODO: deprecate self.demand in favor of
// .demandCommand() .demandOption().
self.demand = self.required = self.require = function (keys, max, msg) {
// you can optionally provide a 'max' key,
...getDemandedCommands = function () { [native code] }...
var defaultGroup = 'Options:'
self.help = function () {
normalizeAliases()
// handle old demanded API
var demandedOptions = yargs.getDemandedOptions()
var demandedCommands = yargs.getDemandedCommands()
var groups = yargs.getGroups()
var options = yargs.getOptions()
var keys = Object.keys(
Object.keys(descriptions)
.concat(Object.keys(demandedOptions))
.concat(Object.keys(demandedCommands))
.concat(Object.keys(options.default))
...getDemandedOptions = function () { [native code] }...
}
var defaultGroup = 'Options:'
self.help = function () {
normalizeAliases()
// handle old demanded API
var demandedOptions = yargs.getDemandedOptions()
var demandedCommands = yargs.getDemandedCommands()
var groups = yargs.getGroups()
var options = yargs.getOptions()
var keys = Object.keys(
Object.keys(descriptions)
.concat(Object.keys(demandedOptions))
.concat(Object.keys(demandedCommands))
...getDetectLocale = function () { [native code] }n/a
getExitProcess = function () { [native code] }...
const logger = yargs._getLoggerInstance()
if (fails.length) {
for (var i = fails.length - 1; i >= 0; --i) {
fails[i](msg, err, self)
}
} else {
if (yargs.getExitProcess()) setBlocking(true)
// don't output failure message more than once
if (!failureOutput) {
failureOutput = true
if (showHelpOnFail) yargs.showHelp('error')
if (msg) logger.error(msg)
if (failMessage) {
...getGroups = function () { [native code] }...
var defaultGroup = 'Options:'
self.help = function () {
normalizeAliases()
// handle old demanded API
var demandedOptions = yargs.getDemandedOptions()
var demandedCommands = yargs.getDemandedCommands()
var groups = yargs.getGroups()
var options = yargs.getOptions()
var keys = Object.keys(
Object.keys(descriptions)
.concat(Object.keys(demandedOptions))
.concat(Object.keys(demandedCommands))
.concat(Object.keys(options.default))
.reduce(function (acc, key) {
...getOptions = function () { [native code] }...
postProcessPositional(yargs, argv, cmd)
addCamelCaseExpansions(argv, cmd)
}
}
// TODO move positional arg logic to yargs-parser and remove this duplication
function postProcessPositional (yargs, argv, key) {
var coerce = yargs.getOptions().coerce[key]
if (typeof coerce === 'function') {
try {
argv[key] = coerce(argv[key])
} catch (err) {
yargs.getUsageInstance().fail(err.message, err)
}
}
...getStrict = function () { [native code] }n/a
getUsageInstance = function () { [native code] }...
// up a yargs chain and possibly returns it.
innerYargs = commandHandler.builder(yargs.reset(parsed.aliases))
// if the builder function did not yet parse argv with reset yargs
// and did not explicitly set a usage() string, then apply the
// original command string as usage() for consistent behavior with
// options object below.
if (yargs.parsed === false) {
if (typeof yargs.getUsageInstance().getUsage() === 'undefined') {
yargs.usage('$0 ' + (parentCommands.length ? parentCommands.join(' ') + ' ' : '') +
commandHandler.original)
}
innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true) : yargs._parseArgs(null, null, true)
} else {
innerArgv = yargs.parsed.argv
}
...getValidationInstance = function () { [native code] }n/a
global = function () { [native code] }...
.getCompletion(['./test.js', '--foo'], function (completions) {
console.log(completions)
})
```
Outputs the same completion choices as `./test.js --foo`<kbd>TAB</kbd>: `--foobar` and `--foobaz`
<a name="global"></a>.global(globals, [global=true])
------------
Indicate that an option (or group of options) should not be reset when a command
is executed, as an example:
```js
var argv = require('yargs')
...group = function () { [native code] }...
```
If the `foo` command is executed the `all` option will remain, but the `none`
option will have been eliminated.
Options default to being global.
<a name="group"></a>.group(key(s), groupName)
--------------------
Given a key, or an array of keys, places options under an alternative heading
when displaying usage instructions, e.g.,
```js
var yargs = require('yargs')(['--help'])
...help = function () { [native code] }...
.usage('Usage: $0 <command> [options]')
.command('count', 'Count the lines in a file')
.example('$0 count -f foo.js', 'count the lines in the given file')
.alias('f', 'file')
.nargs('f', 1)
.describe('f', 'Load a file')
.demandOption(['f'])
.help('h')
.alias('h', 'help')
.epilog('copyright 2015')
.argv;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
...implies = function () { [native code] }...
.usage("$0 -operand1 number -operand2 number -operation [add|subtract]")
.help()
.argv
```
Later on, `argv` can be retrieved with `yargs.argv`.
<a name="implies"></a>.implies(x, y)
--------------
Given the key `x` is set, it is required that the key `y` is set.
Optionally `.implies()` can accept an object specifying multiple implications.
.locale()
...locale = function () { [native code] }...
<a name="implies"></a>.implies(x, y)
--------------
Given the key `x` is set, it is required that the key `y` is set.
Optionally `.implies()` can accept an object specifying multiple implications.
.locale()
---------
Return the locale that yargs is currently using.
By default, yargs will auto-detect the operating system's locale so that
yargs-generated help content will display in the user's language.
...nargs = function () { [native code] }...
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.usage('Usage: $0 <command> [options]')
.command('count', 'Count the lines in a file')
.example('$0 count -f foo.js', 'count the lines in the given file')
.alias('f', 'file')
.nargs('f', 1)
.describe('f', 'Load a file')
.demandOption(['f'])
.help('h')
.alias('h', 'help')
.epilog('copyright 2015')
.argv;
...normalize = function () { [native code] }...
`argv`.
If the function throws, the error will be treated as a validation
failure, delegating to either a custom [`.fail()`](#fail) handler or printing
the error message in the console.
Coercion will be applied to a value after
all other modifications, such as [`.normalize()`](#normalize).
_Examples:_
```js
var argv = require('yargs')
.coerce('file', function (arg) {
return require('fs').readFileSync(arg, 'utf8')
...number = function () { [native code] }...
Optionally `.nargs()` can take an object of `key`/`narg` pairs.
<a name="normalize"></a>.normalize(key)
---------------
The key provided represents a path and should have `path.normalize()` applied.
<a name="number"></a>.number(key)
------------
Tell the parser to always interpret `key` as a number.
If `key` is an array, all elements will be parsed as numbers.
If the option is given on the command line without a value, `argv` will be
...option = function () { [native code] }...
Optionally `.choices()` can take an object that maps multiple keys to their
choices.
Choices can also be specified as `choices` in the object given to `option()`.
```js
var argv = require('yargs')
.option('size', {
alias: 's',
describe: 'choose a size',
choices: ['xs', 's', 'm', 'l', 'xl']
})
.argv
```
...options = function () { [native code] }...
--help Show help [boolean]
Missing required arguments: run, path
Please provide both run and path arguments to work with this tool
```
If a `boolean` value is given, it controls whether the option is demanded;
this is useful when using `.options()` to specify command line parameters.
```javascript
// demand individual options within the option constructor
require('yargs')
.options({
'run': {
alias: 'r',
...parse = function () { [native code] }...
You can pass in the `process.argv` yourself:
````javascript
require('yargs')([ '-x', '1', '-y', '2' ]).argv
````
or use `.parse()` to do the same thing:
````javascript
require('yargs').parse([ '-x', '1', '-y', '2' ])
````
The rest of these methods below come in just before the terminating `.argv`.
...pkgConf = function () { [native code] }...
parser.parse(bot.userText, function (err, argv, output) {
if (output) bot.respond(output)
})
```
***Note:*** Providing a callback to `parse()` disables the [`exitProcess` setting](#exitprocess) until after the callback is invoked
.
.pkgConf(key, [cwd])
------------
Similar to [`config()`](#config), indicates that yargs should interpret the object from the specified key in package.json
as a configuration object.
`cwd` can optionally be provided, the package.json will be read
from this location.
...recommendCommands = function () { [native code] }...
as a configuration object.
`cwd` can optionally be provided, the package.json will be read
from this location.
Note that a configuration stanza in package.json may extend from an identically keyed stanza in another package.json file using
the `"extends"` property. When doing so, the `"extends"` value should be a path (relative or absolute) to the
extended package.json file.
.recommendCommands()
---------------------------
Should yargs provide suggestions regarding similar commands if no matching
command is found?
.require(key, [msg | boolean])
------------------------------
...require = function () { [native code] }...
.recommendCommands()
---------------------------
Should yargs provide suggestions regarding similar commands if no matching
command is found?
.require(key, [msg | boolean])
------------------------------
.required(key, [msg | boolean])
------------------------------
An alias for [`demand()`](#demand). See docs there.
<a name="requiresArg"></a>.requiresArg(key)
...required = function () { [native code] }...
---------------------------
Should yargs provide suggestions regarding similar commands if no matching
command is found?
.require(key, [msg | boolean])
------------------------------
.required(key, [msg | boolean])
------------------------------
An alias for [`demand()`](#demand). See docs there.
<a name="requiresArg"></a>.requiresArg(key)
-----------------
...requiresArg = function () { [native code] }...
.require(key, [msg | boolean])
------------------------------
.required(key, [msg | boolean])
------------------------------
An alias for [`demand()`](#demand). See docs there.
<a name="requiresArg"></a>.requiresArg(key)
-----------------
Specifies either a single option key (string), or an array of options that
must be followed by option values. If any option value is missing, show the
usage information and exit.
The default behavior is to set the value of any key not followed by an
...reset = function () { [native code] }...
Specifies either a single option key (string), or an array of options that
must be followed by option values. If any option value is missing, show the
usage information and exit.
The default behavior is to set the value of any key not followed by an
option value to `true`.
<a name="reset"></a>.reset()
--------
Reset the argument object built up so far. This is useful for
creating nested command line interfaces. Use [global](#global)
to specify keys that should not be reset.
```js
...resetOptions = function () { [native code] }...
output = ''
exitError = null
hasOutput = false
self.parsed = false
return self
}
self.resetOptions()
// temporary hack: allow "freezing" of reset-able state for parse(msg, cb)
var frozen
function freeze () {
frozen = {}
frozen.options = options
frozen.configObjects = options.configObjects.slice(0)
...showCompletionScript = function () { [native code] }...
console.log('world!');
} else {
yargs.showHelp();
}
```
.showCompletionScript()
----------------------
Generate a bash completion script. Users of your application can install this
script in their `.bashrc`, and yargs will provide completion shortcuts for
commands and options.
.showHelp(consoleLevel='error')
...showHelp = function () { [native code] }...
.usage('$0 world')
.help('h')
.example('$0 world', 'print the world message!')
.argv
console.log('world!');
} else {
yargs.showHelp();
}
```
.showCompletionScript()
----------------------
Generate a bash completion script. Users of your application can install this
...showHelpOnFail = function () { [native code] }...
```js
yargs.showHelp("log"); //prints to stdout using console.log()
```
Later on, `argv` can be retrieved with `yargs.argv`.
.showHelpOnFail(enable, [message])
----------------------------------
By default, yargs outputs a usage string if any error is detected. Use the
`.showHelpOnFail()` method to customize this behavior. If `enable` is `false`,
the usage string is not output. If the `message` parameter is present, this
message is output after the error message.
...skipValidation = function () { [native code] }...
```
$ node line_count.js
Missing argument value: f
Specify --help for available options
```
<a name="skipValidation"></a>.skipValidation(key)
-----------------
Specifies either a single option key (string), or an array of options.
If any of the options is present, yargs validation is skipped.
.strict([global=true])
---------
...strict = function () { [native code] }...
<a name="skipValidation"></a>.skipValidation(key)
-----------------
Specifies either a single option key (string), or an array of options.
If any of the options is present, yargs validation is skipped.
.strict([global=true])
---------
Any command-line argument given that is not demanded, or does not have a
corresponding description, will be reported as an error.
`global` indicates whether `strict()` should be enabled both
at the top-level and for each sub-command.
...string = function () { [native code] }...
````javascript
var argv = require('yargs')
.alias('f', 'file')
.demandOption('f')
.default('f', '/etc/passwd')
.describe('f', 'x marks the spot')
.string('f')
.argv
;
````
Optionally `.options()` can take an object that maps keys to `opt` parameters.
````javascript
...terminalWidth = function () { [native code] }...
<a name="wrap"></a>.wrap(columns)
--------------
Format usage output to wrap at `columns` many columns.
By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to
specify no column limit (no right-align). Use `.wrap(yargs.terminalWidth())` to
maximize the width of yargs' usage instructions.
parsing tricks
==============
stop parsing
------------
...updateLocale = function () { [native code] }...
This can be useful if you need to preserve leading zeros in an input.
If `key` is an array, interpret all the elements as strings.
`.string('_')` will result in non-hyphenated arguments being interpreted as strings,
regardless of whether they resemble numbers.
.updateLocale(obj)
------------------
.updateStrings(obj)
------------------
Override the default strings used by yargs with the key/value
pairs provided in `obj`:
...updateStrings = function () { [native code] }...
If `key` is an array, interpret all the elements as strings.
`.string('_')` will result in non-hyphenated arguments being interpreted as strings,
regardless of whether they resemble numbers.
.updateLocale(obj)
------------------
.updateStrings(obj)
------------------
Override the default strings used by yargs with the key/value
pairs provided in `obj`:
```js
var argv = require('yargs')
...usage = function () { [native code] }...
-------------------------------------------------
area.js:
````javascript
#!/usr/bin/env node
var argv = require('yargs')
.usage('Usage: $0 -w [num] -h [num]')
.demandOption(['w','h'])
.argv;
console.log("The area is:", argv.w * argv.h);
````
***
...version = function () { [native code] }...
Set a usage message to show which commands to use. Inside `message`, the string
`$0` will get interpolated to the current script name or node command for the
present script similar to how `$0` works in bash or perl.
`opts` is optional and acts like calling `.options(opts)`.
<a name="version"></a>.version([option], [description], [
version])
----------------------------------------
Add an option (e.g. `--version`) that displays the version number (given by the
`version` parameter) and exits the process.
If no arguments are passed to `version` (`.version()`), yargs will parse the `package.json`
of your module and use its `version` value. The default value of `option` is `--version`.
...wrap = function () { [native code] }...
builder: (yargs) => yargs.default('value', 'true'),
handler: (argv) => {
console.log(`setting ${argv.key} to ${argv.value}`)
}
})
.demandCommand()
.help()
.wrap(72)
.argv
```
```
$ ./svc.js help
Commands:
start [app] Start up an app [aliases: run, up]
...function YError(msg) {
this.name = 'YError'
this.message = msg || 'yargs error'
Error.captureStackTrace(this, YError)
}n/a
function Yargs(processArgs, cwd, parentRequire) {
processArgs = processArgs || [] // handle calling yargs().
const self = {}
var command = null
var completion = null
var groups = {}
var output = ''
var preservedGroups = {}
var usage = null
var validation = null
const y18n = Y18n({
directory: path.resolve(__dirname, './locales'),
updateFiles: false
})
if (!cwd) cwd = process.cwd()
self.$0 = process.argv
.slice(0, 2)
.map(function (x, i) {
// ignore the node bin, specify this in your
// bin file with #!/usr/bin/env node
if (i === 0 && /\b(node|iojs)(\.exe)?$/.test(x)) return
var b = rebase(cwd, x)
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x
})
.join(' ').trim()
if (process.env._ !== undefined && process.argv[1] === process.env._) {
self.$0 = process.env._.replace(
path.dirname(process.execPath) + '/', ''
)
}
// use context object to keep track of resets, subcommand execution, etc
// submodules should modify and check the state of context as necessary
const context = { resets: -1, commands: [], files: [] }
self.getContext = function () {
return context
}
// puts yargs back into an initial state. any keys
// that have been set to "global" will not be reset
// by this action.
var options
self.resetOptions = self.reset = function (aliases) {
context.resets++
aliases = aliases || {}
options = options || {}
// put yargs back into an initial state, this
// logic is used to build a nested command
// hierarchy.
var tmpOptions = {}
tmpOptions.local = options.local ? options.local : []
tmpOptions.configObjects = options.configObjects ? options.configObjects : []
// if a key has been explicitly set as local,
// we should reset it before passing options to command.
var localLookup = {}
tmpOptions.local.forEach(function (l) {
localLookup[l] = true
;(aliases[l] || []).forEach(function (a) {
localLookup[a] = true
})
})
// preserve all groups not set to local.
preservedGroups = Object.keys(groups).reduce(function (acc, groupName) {
var keys = groups[groupName].filter(function (key) {
return !(key in localLookup)
})
if (keys.length > 0) {
acc[groupName] = keys
}
return acc
}, {})
// groups can now be reset
groups = {}
var arrayOptions = [
'array', 'boolean', 'string', 'requiresArg', 'skipValidation',
'count', 'normalize', 'number'
]
var objectOptions = [
'narg', 'key', 'alias', 'default', 'defaultDescription',
'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce'
]
arrayOptions.forEach(function (k) {
tmpOptions[k] = (options[k] || []).filter(function (k) {
return !localLookup[k]
})
})
objectOptions.forEach(function (k) {
tmpOptions[k] = objFilter(options[k], function (k, v) {
return !localLookup[k]
})
})
tmpOptions.envPrefix = options.envPrefix
options = tmpOptions
// if this is the first time being executed, create
// instances of all our helpers -- otherwise just reset.
usage = usage ? usage.reset(localLookup) : Usage(self, y18n)
validation = validation ? validation.reset(localLookup) : Validation(self, usage, y18n)
command = command ? command.reset() : Command(self, usage, validation)
if (!completion) completion = Completion(self, usage, command)
if (!strictGlobal) strict = false
completionCommand = null
output = ''
exitError = null
hasOutput = false
self.parsed = false
return self
}
self.resetOptions()
// temporary hack: allow "freezing" of reset-able state for parse(msg, cb)
var frozen
function freeze () {
frozen = {}
frozen.options = options
frozen.configObjects = options.configObjects.slice(0)
frozen.exitProcess = exitProcess
frozen.groups = groups
usage.freeze()
validation.freeze()
command.freeze()
frozen.strict ...n/a
function rebase(base, dir) {
return path.relative(base, dir)
}n/a
function YError(msg) {
this.name = 'YError'
this.message = msg || 'yargs error'
Error.captureStackTrace(this, YError)
}n/a
function YError(msg) {
this.name = 'YError'
this.message = msg || 'yargs error'
Error.captureStackTrace(this, YError)
}n/a