我正在尝试创建一个小的构建脚本,如果没有在默认路径中找到它们,它将询问用户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)
}
}
]
答案 0 :(得分:3)
怎么样:
object
或更简洁地说:
>>> A = np.array([[1,2,3],
... [1,2,3],
... [1,2,3]])
>>> A
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
或更一般地,在lodash的帮助下,类似:
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
})
和一个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
})
,否则它们可能会隐藏其默认值,从而将其默认值强制包含在答案中。