I am trying to implement a simple yes/no script.
A function runs, then the user is prompt to input whether or not to run it again.
If the user inputs "y", then the procedure should repeat.
If the user inputs "n", then the procedure should terminate.
If neither, then the question should repeat.
Here is my 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);
Unfortunately, the process always terminates at the second time the question is asked.
I tried removing the process.stdin.end()
part, and I got a really weird behavior:
First time I input "y", the question is asked once and the function runs once.
Second time I input "y", the question is asked twice and the function runs twice.
Third time I input "y", the question is asked thrice and the function runs thrice.
In addition, at some point I start getting this error:
(node:12336) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 data listeners added. Use emitter.setMaxListeners() to increase limit
Can anybody please shed some light on what's going on here?
Any suggestions on how to make this work will be very much apprteciated.
Thank you!!!
The line
prevents further input, and (here) effectively ends the program. So, you'll want to call it only once, once everything is done. The
command adds a listener to when the user presses "enter". If you call this multiple times, multiple listeners will be added.
So, you might consider adding just one listener, calling
process.stdin.end();
if the response isn
:Output example: