Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

example using inquirer to prompt user #2385

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 44 additions & 0 deletions docs/advanced.md
Expand Up @@ -617,3 +617,47 @@ try {
}
console.info('finish')
```

### Using Inquirer to make interactive tools

Using Inquirer or a similar package with yargs is a powerful way to make your CLI tools more interactive and responsive to the user.

One example would be to use `input` to ensure the user inputs required arguments.

```js
import yargs from 'yargs/yargs';
import { hideBin } from 'yargs/helpers';
import { input } from '@inquirer/prompts';

await yargs(hideBin(process.argv))
.command({
command: 'login [username]',
describe: 'Log in with defined username',
builder: (yargs) => {
yargs.positional('username', {
describe: 'The username used to log in',
type: 'string',
});
},
handler: async (argv) => {
if (!argv.username) {
argv.username = await input({ message: 'Please enter your username' });
}

console.log(`Welcome back, ${argv.username}!`);
},
})
.help()
.parse();
```

If username is not given as an argument, inquirer will prompt the user with an input.

```
$ ./app.js login
? Please enter your username: yargs
Welcome back, yargs!

$ ./app.js login yargs
Welcome back, yargs!
```