Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading