4

我正在尝试创建一个小型构建脚本,如果在默认路径中找不到它们,它将向用户询问 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)
    }
  }
]
4

1 回答 1

4

怎么样:

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
  })

最后一个解决方案应该导致任何带有 adefault和 a 的问题when,否则它可能会隐藏其默认值,将其默认值强制包含在答案中。

于 2018-10-16T19:17:22.067 回答