1

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()
Alex K
  • 61
  • 6

1 Answers1

1

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);
theusaf
  • 1,781
  • 1
  • 9
  • 19
  • the solution you offered @theusaf seems logical.. it doesnt throw warning anymore, but it still seem to run infinite times ( at least a lot more then 10) from my tests . the exit condition doesn't seem to work – Alex K Aug 25 '21 at 22:06
  • Oh, my bad. I made a small mistake. I'll fix it quickly – theusaf Aug 25 '21 at 22:11
  • it resolved it, thank you! I am a little curious to know what u changed that stopped it from looping infinitely, because I don't see a difference honestly @theusaf – Alex K Aug 25 '21 at 23:08
  • Previously, I had done `timesLeft--`, which passes in the current value before decrementing it, which is why it went on forever. I changed it to `--timesLeft` to decrement, then pass in the value. – theusaf Aug 25 '21 at 23:10
  • while on the topic, why recursion work in this case but for loop doesn't? what am i missing? what topic should i reference? (should i post this as a question?) – Alex K Aug 29 '21 at 14:04
  • The loop doesn't work because `readline.question()` is not synchronous, meaning your earlier implementation would create a bunch of interfaces and questions at the same time. If you want to use a loop, you can wrap `readline.question()` into a `Promise` and use `async`/`await`. – theusaf Aug 29 '21 at 15:41