简体   繁体   中英

Asking the user to confirm before executing the code using Yargs

Using yargs is it possible for the user of the CLI to specify which command they want to call with the arguments and then the CLI replies with the following message before running the code:

Are you sure you want to execute this code on environment X with these settings: .... Y / N:

Y would execute the code N would do nothing

Update: Just found an npm modulecalled yargs-interactive. I think this is the answer to my question.

const yargsInteractive = require(‘yargs-interactive’);
const options = {
  name: { 
    type: ‘input’, 
    default: ‘A robot’, 
    describe: ‘Enter your name’
  },
  likesPizza: { 
    type: ‘confirm’, 
    default: false, 
    describe: ‘Do you like pizza?’
  },
};
yargsInteractive()
  .usage(‘$0 <command> [args]’)
  .interactive(options)
  .then((result) => {
    // Your business logic goes here.
    // Get the arguments from the result
    // (e.g. result.name)
    console.log(result.name);
});

I was not able to find anything in yargs itself to do this. So I just used Node's readline module:

import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'


async function confirm(question) {
  const line = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  })

  return new Promise((resolve) => {
    line.question(question, (response) => {
      line.close()
      resolve(response === 'Y')
    })
  })
}

async function handleRemove(argv) {
  const confirmed = await confirm(`Are you sure you want to remove the stuff? [Y/n]`)

  if (confirmed) {
    // Remove everything
  }
}

yargs(hideBin(process.argv))
  .command({
    command: 'remove',
    describe: 'Remove important stuff',
    handler: handleRemove,
  })
  .showHelpOnFail(true)
  .scriptName('cli')
  .demandCommand()
  .help().argv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM