在Node中使用readline提示符/ setPrompt时无法清除行

使用readline prompt时,我无法清除stdout的一行。

我的代码类似于这样的:

 import readline from 'readline' const rl = readline.createInterface(process.stdin, process.stdout) let input = '' readline.emitKeypressEvents(process.stdin) process.stdin.on('keypress', registerInput) function registerInput (str, key) { if (key.name === 'backspace') { input = input.slice(0, input.length - 1) } else { input += str } if (input === '42') { input = '' console.log(' ✓') nextPrompt() } } function nextPrompt () { readline.clearLine(process.stdout, 0) rl.setPrompt('What is the meaning of life? ') rl.prompt() } nextPrompt() 

在真实的代码中,生成算术问题。

这是输出的屏幕截图 。

怎么了

光标重置(使用.prompt(false)将光标保持在位置),但input仍然存在于新提示中。

预期

input42不应出现在下一行的新提示中。

为什么我使用.on('keypress'而不是rl.on('line' ?我希望游戏中的响应快速,避免按下input

我曾经尝试过:

  • readline.clearLine(process.stdout, -1)
  • readline.clearLine(process.stdout, 1)
  • readline.clearLine(process.stdin, 0)
  • process.stdout.clearLine()

环境

我正在使用节点v6.0.0和babel-cli v6.7.7(这里的babel只是为了导入语句,但在实际的代码中我使用了object-rest-spread ,因此需要babel)。 如果你没有安装babel, 这是生成的代码的要点 。

rl.promptreadline.clearLine不兼容? 这怎么解决?

我解决了这个问题:

 import readline from 'readline' let input = '' let question = 'What is the meaning of life? ' const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) readline.emitKeypressEvents(process.stdin) process.stdin.on('keypress', registerInput) function registerInput (str, key) { if (key.name === 'backspace') { input = input.slice(0, input.length - 1) } else { const numbers = '1 2 3 4 5 6 7 8 9 0'.split(' ') if (numbers.indexOf(str) !== -1) { input += str } } if (input === '42') { console.log(' ✓') input = '' } render(question, input) } function render (question, input) { readline.clearLine(process.stdout, 0) readline.cursorTo(process.stdout, 0) process.stdout.write(question + input) } render(question, input) 

但问题仍然存在,为什么rl.promptreadline.clearLine不兼容?

我猜测prompt和幕布背后的做法类似。 resetPromptInput会很好。