javascript - NodeJS : How to re-display custom CLI menu after executing corresponding functionality

标签 javascript node.js command-line-interface

我是底层编程出身,所以 JS 和 NodeJS 对我来说是一个新的境界。

我正在尝试创建一个应用程序,该应用程序首先向用户显示 CLI 菜单。当用户选择菜单选项时,将执行相应的功能。该功能完成后,我希望重新显示菜单。

在 Python 和嵌入式 C 中处理此问题的一个非常简单的方法是将菜单包含在 while(1) 循环中,然后在用户选择相应的菜单选项时终止程序/脚本进程。然而,在 NodeJS 中,您无法在 while(1) 循环中运行菜单——与每个菜单选项相对应的调用函数实际上从未被调用,菜单只是立即重新显示。

换句话来说,NodeJS 相当于:

while(1) {
  displayMenuToUser();
  // Wait for user to select which menu option they want
  if (quitMenuOptionSelectedByUser) {
    terminateProcess();
  } else {
    executeFunctionCorrespondingToTheSelectedMenuOption();
    // At this point the menu should be re-displayed so the user can select another option
  }
}

最佳答案

您可以使用Inquirer.js

我制作了这个示例,如果您对再去一次?问题回答,该示例将继续循环:

var inquirer = require('inquirer');

const showMenu = () => {
    inquirer
    .prompt([{
        name: 'age',
        type: 'input',
        message: 'What\'s your age?',
    }, {
        name: 'country',
        type: 'list',
        message: 'Where do you live?',
        choices: ['USA', 'China', 'Germany', 'France'],
    }, {
        name: 'back',
        type: 'input',
        message: 'Go again?',
        choices: ['yes', 'no'],
    }]
    ).then((answers) => {
        console.log(`\nMy age is ${answers.age} and I live in ${answers.country}.\n`);
        if (answers.back === 'yes') {
            return showMenu();
        }
    })
    .catch((err) => {
        console.log(err);
    });
}

showMenu();

关于javascript - NodeJS : How to re-display custom CLI menu after executing corresponding functionality,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58442756/

相关文章:

javascript - 使用 parallax.min.js 将空白添加到视差 div

node.js - 将带有正文的 POST XMLHttpRequest 发送到快速 Node 服务器

javascript - 强制 Protractor 的 onPrepare 等待异步 http 请求

javascript - Jquery:从获取请求更改 jqXHR 的 HTML 内容

javascript - 使用 fullPage.js 定位导航栏

node.js - mongodb中的聚合函数

python - 如何从 Python 脚本执行 Cassandra CLI 命令?

linux - 如何使用键盘将终端中的所有内容复制/粘贴到记事本?

python - 语法错误 : mismatched input 'print' expecting INDENT

javascript - TSC 正在根据 tsconfig.json 文件的方向编译 node_modules 和类型声明文件