使用 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/