title: A simple yes/no script yields weird behavior
body: <p>I am trying to implement a simple yes/no script.</p>
  
  <p>A function runs, then the user is prompt to input whether or not to run it again.</p>
  
  <p>If the user inputs "y", then the procedure should repeat.</p>
  
  <p>If the user inputs "n", then the procedure should terminate.</p>
  
  <p>If neither, then the question should repeat.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>function func(i) {
      console.log(i);
      ask(i + 1);
  }
  
  function ask(i) {
      process.stdout.write("again (y/n)?");
      process.stdin.on("data", function(data) {
          process.stdin.end();
          if (data.toString().trim() == "y")
              func(i);
          else if (data.toString().trim() != "n")
              ask(i);
      });
  }
  
  func(0);
  </code></pre>
  
  <p>Unfortunately, the process always terminates at the second time the question is asked.</p>
  
  <p>I tried removing the <code>process.stdin.end()</code> part, and I got a really weird behavior:</p>
  
  <p>First time I input "y", the question is asked once and the function runs once.</p>
  
  <p>Second time I input "y", the question is asked twice and the function runs twice.</p>
  
  <p>Third time I input "y", the question is asked thrice and the function runs thrice.</p>
  
  <p>In addition, at some point I start getting this error:</p>
  
  <blockquote>
    <p>(node:12336) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 data listeners added. Use emitter.setMaxListeners() to increase limit</p>
  </blockquote>
  
  <p>What might be going on here?</p>