[英]How to take user input in Node.js - ESM not CJS
I am doing a project where I am supposed to create a JavaScript RPG CLI game using Node.js. I am supposed to use ESM and not CommonJS.我正在做一个项目,我应该使用 Node.js 创建一个 JavaScript RPG CLI 游戏。我应该使用 ESM 而不是 CommonJS。 Once executed, the script has to output Welcome with a menu underneath where you choose to either start the game, load or exit the game.执行后,脚本必须显示 output欢迎,您可以在下方的菜单中选择开始游戏、加载或退出游戏。 Then, it demands user input to choose an option.然后,它要求用户输入以选择一个选项。
I have put type: 'module'
in my package.json to use ESM.我已将type: 'module'
放入我的 package.json 以使用 ESM。 I tried with readline and with inquirer.js but nothing works.我尝试使用readline和 inquirer.js,但没有任何效果。 I installed inquirer.js with npm i inquirer
, imported it but it doesn't work.我用npm i inquirer
安装了 inquirer.js,导入它但它不起作用。 I literally just started this project, I basically have but few lines of the code.我真的刚刚开始这个项目,我基本上只有几行代码。 I don't know where the problem is.我不知道问题出在哪里。
Here is one of the codes that I tried:这是我尝试过的代码之一:
import readline from "readline";
import { stdin as input, stdout as output } from "node:process";
const run = (args) => {
console.clear();
console.log(`
+-----------------------------+
| Welcome ! |
+-----------------------------+
`);
console.log(`
1. Start game 👍
2. Load game 💾
3. Exit ❌
`);
const rl = readline.createInterface({ input, output });
rl.question("Your choice (1-3): ");
rl.close();
};
export default run;
Does this help?这有帮助吗?
import readline from "readline";
import { stdin as input, stdout as output } from "node:process";
const run = (args) => {
console.clear();
console.log(`
+-----------------------------+
| Welcome ! |
+-----------------------------+
`);
console.log(`
1. Start game 👍
2. Load game 💾
3. Exit ❌
`);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Your choice (1-3): ", (in)=>{
//your code here
// example:
switch () {
case 1:
start();
break();
case 2:
load();
break();
case 3:
exit();
break();
}
rl.close()
});
};
export default run;
Of course you need to create start()
, load()
and exit()
functions当然,您需要创建start()
、 load()
和exit()
函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.