Node.js prompt-sync repeats prompt when using newl

2019-08-26 12:59发布

问题:

I'm working on a JavaScript assignment that requires me to use prompt-synch in Node.JS. It works fine until I try to use a newline character \n within the prompt, at which point every character or backspace typed causes the prompt to repeat itself.

What could I do to get the user input to appear on a new line (a requirement of this exercise) without this issue?

Problem code:

if (guess < answer) {
  guess = prompt("Too low!\n> ");
} else if (guess > answer) {
  guess = prompt("Too high!\n> ");
}

output screenshot

回答1:

You can try this instead.

if (guess < answer) {
  console.log("Too low!");
  guess = prompt("> ");
} else if (guess > answer) {
  console.log("Too high!");
  guess = prompt("> ");
}

If this does not work then it is likely an issue with another part of your own code. If it does, then it is likely an issue with the prompt-sync module, which makes this a valid workaround if you believe it is.