Search code examples
javascriptnode.jsloopsreadline

read user input N times from console node js


I'm trying to get an input from a user to a console in node js a finite number of times, and run a function on each input. while or for loop doesn't work.

any help?

here is my code (litle simplified):

function foo(num)
{
 console.log(num)
}

function ReadUseInput()
{
 const readline = require('readline').createInterface({
     input: process.stdin,
    output: process.stdout
   }); 
    readline.question('Enter number...', num => 
  {
         foo(num)
       readline.close();
     });
}

//for (var i = 0; i < 10; i++)// this line isnt working - shows warning: MaxListenersExceededWarning: Possible EventEmitter memory leak detected
ReadUseInput()

Solution

  • One solution could be to make the ReadUseInput() function take a number and decrement it to repeat a certain number of times:

    function foo(num) {
     console.log(num)
    }
    
    function ReadUseInput(timesLeft) {
      // exit condition
      if(timesLeft <= 0) {
        return;
      }
      const readline = require('readline').createInterface({
        input: process.stdin,
        output: process.stdout
      }); 
      readline.question('Enter number...', num => {
        foo(num)
        readline.close();
        ReadUseInput(--timesLeft);
      });
    }
    
    ReadUseInput(10);