我是底层编程出身,所以 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/