Home > Mobile >  node app to prompt user to enter an input
node app to prompt user to enter an input

Time:10-16

I am new to node.js and was trying to implement a simple app in which the user should be prompted to enter the direction in which they want to move but it does not work. Any suggestions would be greatly appreciated.

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
///////////////////////////////////////////
const handleInput = (userInput) => {
  const str = userInput.toString().trim();
  let output;
  if (process.argv[2] === 'up') {
    output = ///move up
  } 
  if (process.argv[2] === 'right') {
    output = ///move to the right
  } 
  if (process.argv[2] === 'left') {
    output = ///move to the left
  } 
  
  process.stdout.write(output   '\n');
  process.exit();
}

// Run the program.
process.stdout.write('Which direction do you want to move ?\n> ');
process.stdin.on('data', handleInput);

CodePudding user response:

You have to use readline.Interface.question instead of process.stdin.on.

Try the following code (and change it for your needs):

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("Which direction do you wanna move ? ", (userInput) => {
    const str = userInput.toString().trim();
    let output;
    if (str === 'up') {
      output = "move up";
    } 
    if (str === 'right') {
      output = "move to the right";
    } 
    if (str === 'left') {
      output = "move to the left";
    } 
    
    console.log(output   "\n");
    rl.close();
});

rl.on("close", () => {
    console.log("\nBYE BYE !!!");
    process.exit(0);
});

I hope this helps.

  • Related