【问题标题】:How to set default value for an answer using inquirer?如何使用查询器设置答案的默认值?
【发布时间】:2018-10-17 21:58:31
【问题描述】:

我正在尝试创建一个小型构建脚本,如果在默认路径中找不到它们,它将询问用户 mysql 标头的位置。现在我正在使用inquirer 提示用户输入,这工作正常,但我遇到了以下问题:

'use strict'
const inquirer = require('inquirer')
const fs = require('fs')

const MYSQL_INCLUDE_DIR = '/usr/include/mysql'

let questions = [
  {
    type: 'input',
    name: 'MYSQL_INCLUDE_DIR',
    message: 'Enter path to mysql headers',
    default: MYSQL_INCLUDE_DIR,
    when: (answers) => {
      return !fs.existsSync(MYSQL_INCLUDE_DIR)
    },
    validate: (path) => {
      return fs.existsSync(path)
    }
  }
]

inquirer.prompt(questions)
  .then((answers) => {
    // Problem is that answers.MYSQL_INCLUDE_DIR might be undefined at this point.
  })

如果找到 mysql 标头的默认路径,则不会显示问题,因此不会设置答案。如何在不实际向用户显示的情况下为问题设置默认值?

解决上述问题也可以做到这一点,而不是使用全局变量:

let questions = [
  {
    type: 'input',
    name: 'MYSQL_INCLUDE_DIR',
    message: 'Enter path to mysql headers',
    default: MYSQL_INCLUDE_DIR,
    when: (answers) => {
      return !fs.existsSync(answers.MYSQL_INCLUDE_DIR)
    },
    validate: (path) => {
      return fs.existsSync(path)
    }
  }
]

【问题讨论】:

    标签: node.js node-modules fs inquirer


    【解决方案1】:

    怎么样:

    inquirer.prompt(questions)
      .then((answers) => {
        const mysqlIncludeDir = answers && answers.MYSQL_INCLUDE_DIR ? answers.MYSQL_INCLUDE_DIR : MYSQL_INCLUDE_DIR;
      })
    

    或者更简洁:

    inquirer.prompt(questions)
      .then((answers) => {
        const theAnswers = {
          MYSQL_INCLUDE_DIR,
          ...answers
        };
        // theAnswers should be the answers you want
        const mysqlIncludeDir = theAnswers.MYSQL_INCLUDE_DIR;
        // mysqlIncludeDir should now be same as first solution above
      })
    

    或者更一般地在 lodash 的帮助下,例如:

    const myPrompt = (questions) => inquirer.prompt(questions)
      .then((answers) => {
        return {
          ...(_.omitBy(_.mapValues(_.keyBy(questions, 'name'), 'default'), q => !q)),
          ...answers
        };
      })
    
    myPrompt(questions)
      .then((answers) => {
        // should be the answers you want
      })
    

    最后一个解决方案应该引起defaultwhen的任何问题,否则可能会隐藏其默认值,将其默认值强制包含在答案中。

    【讨论】:

    • 是的,我当然可以这样做,但我希望有更好的方法来实现这一点 =)
    • 明白了,正在寻找一种库支持/流畅的方式,嗯?
    • 我只是在想是否有更好的方法来做到这一点,实际上认为答案没有设置为默认值作为标准似乎很奇怪。
    • 添加了一些更优雅的想法
    • 我不太确定你的意思是我应该在你的第二个例子中做什么const theAnswers?
    猜你喜欢
    • 2019-09-02
    • 2020-01-07
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多