javascript - 使用 Yargs 执行代码之前要求用户确认

标签 javascript node.js command-line-interface yargs

使用 yargs,CLI 用户可以指定他们想要使用参数调用哪个命令,然后 CLI 在运行代码之前回复以下消息:

您确定要使用以下设置在环境 X 上执行此代码吗:... 是/否:

Y 将执行代码 N什么也不做

更新: 刚刚发现一个名为 yargs-interactive 的 npm 模块。我想这就是我问题的答案。

最佳答案

我无法在 yargs 本身中找到任何内容来执行此操作。所以我只使用了 Node 的 readline模块:

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

关于javascript - 使用 Yargs 执行代码之前要求用户确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64465406/

相关文章:

java - Apache 命令行解析器错误?

javascript - 如何为单个图像触发 html 或 javascript 中的灯箱画廊?

涉及方法的 JavaScript 比较永远不会为真

javascript - 使用 Bower 优于 Git 子模块的好处

node.js - 为什么等待函数返回挂起的 promise

java - com.datastax.driver.core.exceptions.InvalidQueryException 使用 Datastax Java 驱动程序

javascript - 将 Javascript 中的当前时间传递给 GraphQL AWSDateTime 列

javascript - 获取数字的每一位数字

node.js - 从 Google App Engine 访问 Google Firebase 托管时出现 502 Bad Gateway 错误

command-line - Mac Terminal-如何在CLI上启动Android Virtual Device Manager?