Skip to content

Commit

Permalink
docs: only use parse and argv at top level (#1990)
Browse files Browse the repository at this point in the history
  • Loading branch information
jly36963 committed Sep 5, 2021
1 parent d0e8292 commit 9d0d6fa
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/api.md
Expand Up @@ -87,6 +87,8 @@ If `yargs` is executed in an environment that embeds node and there's no script
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.

***Note:*** `.argv` should only be used at the top level, not inside a command's builder function.

<a name="array"></a>.array(key)
----------

Expand Down Expand Up @@ -336,6 +338,8 @@ yargs
.argv
```

***Note:*** `.parse()` and `.argv` should only be used at the top level, not inside a command's builder function.

Please see [Advanced Topics: Commands](https://github.com/yargs/yargs/blob/master/docs/advanced.md#commands) for a thorough
discussion of the advanced features exposed in the Command API.

Expand Down Expand Up @@ -1344,6 +1348,8 @@ the resulting error and output will not be passed to the `parse()` callback (the
returning a promise. If your use case requires `parse()` to be called several times, any asynchronous
operation performed in a command handler should not result in the handler returning a promise.

***Note:*** `.parse()` should only be used at the top level, not inside a command's builder function.

.parseAsync([args], [context], [parseCallback])
------------

Expand Down
54 changes: 54 additions & 0 deletions example/nested.js
@@ -0,0 +1,54 @@
const argv = require('yargs/yargs')(process.argv.slice(2)).command(
'math',
'math description',
yargs =>
yargs
.command(
'add <a> <b>',
'add description',
yargs =>
yargs
.positional('a', {
describe: 'addend "a"',
type: 'number',
default: 0,
})
.positional('b', {
describe: 'addend "b"',
type: 'number',
default: 0,
}),
argv => {
const {a, b} = argv;
console.log(`${a} + ${b} = ${a + b}`);
}
)
.command(
'sum <numbers..>',
'sum description',
yargs =>
yargs
.positional('numbers', {
describe: 'numbers to sum',
type: 'array',
default: [],
})
.check(argv =>
isArrayOfNumbers(argv.numbers)
? true
: 'Positional argument "numbers" must only contain numbers'
),
argv => {
const sum = argv.numbers.reduce((a, b) => a + b, 0);
console.log(`The sum of numbers is ${sum}`);
}
)
).argv;

console.log(argv);

function isArrayOfNumbers(arr) {
return Array.isArray(arr) && arr.every(n => typeof n === 'number');
}

// NOTE: ".argv" and ".parse()" should only be used at top level, not inside builder functions.

0 comments on commit 9d0d6fa

Please sign in to comment.