Thanks to visit codestin.com
Credit goes to GitHub.com

Skip to content

Conversation

@nephh
Copy link
Contributor

@nephh nephh commented Jan 8, 2024

Added a simple example of using Inquirer prompts to ensure the user inputs a required argument.

@shadowspawn
Copy link
Member

I wonder whether the inquirer prompts would work well in a middleware callback so "outside" the handler. But not sure makes any practical difference! I'll do a little digging...

@shadowspawn
Copy link
Member

Putting the code in middleware does work fine but I didn't find an advantage other than the separation, so probably better keeping the code simpler.

@nephh
Copy link
Contributor Author

nephh commented Jan 9, 2024

I did notice some things with async await if we wanted to say access username later on in a different function. We would just need to await the whole yargs function, something like this (in order to console.log out the username):

const argv = await yargs(hideBin(process.argv))
  .command({
    command: "login [username]",
    describe: "Prints out the username",
    builder: (yargs) => {
      yargs.positional("username", {
        describe: "The username to be printed",
        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();

console.log(argv.username);

Would it be helpful to mention this in this inquirer section? There might be more specific documentation on async await so it might not be needed.

@shadowspawn
Copy link
Member

Good question about async. I don't think need to explicitly refactor code or explain about async since main point of example is inquirer, but I do think should add await in example code as good practice when have an async handler.

await yargs(hideBin(process.argv))
...

@nephh
Copy link
Contributor Author

nephh commented Jan 10, 2024

Sounds good, thanks for all the help. Went ahead and pushed those changes

Copy link
Member

@shadowspawn shadowspawn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me.

Thanks @nephh

@bcoe bcoe changed the title example using inquirer to prompt user docs: an example of using inquirer to prompt user Apr 9, 2025
@bcoe bcoe merged commit 576236e into yargs:main Apr 9, 2025
6 checks passed
@bcoe
Copy link
Member

bcoe commented Apr 9, 2025

@nephh thank you for the contribution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants