首页 > 解决方案 > 如何将参数传递给询问者问题?

问题描述

如何将参数传递给询问者问题,以便我可以根据先前问题的值或提示之外的代码设置问题对象的值?

如果基于上一个问题的答案,我能看到实现此目的的唯一方法是嵌套查询器提示调用

const inquirer = require('inquirer');

function getPath(){
    return {
        'system1':`system1path`,
        'system2':`system2path`,
        'system3':`system3path`
    }
}

inquirer.prompt([
     {
        type: 'list',
        name: 'testSystem',
        message: 'Which system do you want to run?',
        choices: ['system1', 'system2', 'system3']
    },
    {
        type: 'fuzzypath',
        name: 'searchTestSuite',
        excludePath: nodePath => nodePath.startsWith('node_modules'),
        itemType: 'any',
        rootPath: getPath()['< answer from question(testSystem) >'],
        message: 'Select a target directory :',
        default: `system1path`,
        suggestOnly: false,
        depthLimit: 6,
    },

]).then(answers => {
    console.log(answers);
});

预期结果:如果您选择 testSystem = system2 您应该得到 rootPath = system2Path ,而不嵌套查询器提示或使用when函数(因为when似乎正在处理布尔值)

标签: javascriptpromiseinquirerjs

解决方案


您可以通过嵌套来解决它​​,但将 from 更改Promise.thenasync-await使其更具可读性。Inquirer.js 使用 Promise,因此您可以使用 await 来捕获提示答案,并通过发出多个提示,您可以保存提示之间的状态。请参阅下面的代码。

PS:我已经default: ...,从fuzzypath 中删除了该参数,因为它产生了默认值,尽管它在根路径之外。

const inquirer = require('inquirer');
inquirer.registerPrompt('fuzzypath', require('inquirer-fuzzy-path'))

const system1path = ...;
const system2path = ...;
const system3path = ...;

function getPath(){
    return {
        'system1': `${system1path}`,
        'system2': `${system2path}`,
        'system3': `${system3path}`
    };
}

(async function () {
    const {testSystem} = await inquirer.prompt({
        type: 'list',
        name: 'testSystem',
        message: 'Which system do you want to run?',
        choices: ['system1', 'system2', 'system3']
    });
    const {searchTestSuite} = await inquirer.prompt({
        type: 'fuzzypath',
        name: 'searchTestSuite',
        excludePath: nodePath => nodePath.startsWith('node_modules'),
        itemType: 'any',
        rootPath: getPath()[testSystem],
        message: 'Select a target directory :',
        suggestOnly: false,
        depthLimit: 6,
    });
    console.log({testSystem, searchTestSuite});
})();


推荐阅读