在 Node 中使用 readline prompt/setPrompt 时无法清除行

arv*_*ve0 5 console prompt node.js

我在stdout使用readline prompt.

我的代码类似于:

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()
Run Code Online (Sandbox Code Playgroud)

在实际代码中,会生成算术问题。

这是输出的屏幕截图

发生什么了

光标重置(使用.prompt(false)保持光标在位),但输入仍在新提示中。

预期的

输入42不应出现在下一行的新提示中。

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

我尝试过的:

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

环境

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

rl.prompt不兼容的readline.clearLine?如何解决这个问题?

arv*_*ve0 3

我是这样解决的:

\n\n
import readline from 'readline'\n\nlet input = ''\nlet question = 'What is the meaning of life? '\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n})\nreadline.emitKeypressEvents(process.stdin)\nprocess.stdin.on('keypress', registerInput)\n\nfunction registerInput (str, key) {\n  if (key.name === 'backspace') {\n    input = input.slice(0, input.length - 1)\n  } else {\n    const numbers = '1 2 3 4 5 6 7 8 9 0'.split(' ')\n    if (numbers.indexOf(str) !== -1) {\n      input += str\n    }\n  }\n  if (input === '42') {\n    console.log(' \xe2\x9c\x93')\n    input = ''\n  }\n  render(question, input)\n}\n\nfunction render (question, input) {\n  readline.clearLine(process.stdout, 0)\n  readline.cursorTo(process.stdout, 0)\n  process.stdout.write(question + input)\n}\n\nrender(question, input)\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

我猜这prompt与我在幕后的做法类似。一个resetPromptInput会很好。

\n