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. 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. Then, it demands user input to choose an option.
I have put type: 'module' in my package.json to use ESM. I tried with readline and with inquirer.js but nothing works. I installed inquirer.js with npm i inquirer, imported it but it doesn’t work. 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;
>Solution :
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