【发布时间】:2016-08-29 02:32:25
【问题描述】:
我在使用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()
在真实代码中,生成算术题。
Here is a screen capture of the output.
会发生什么
光标重置(使用.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 仅用于 import 语句,但在实际代码中我使用 object-rest-spread 因此需要 babel)。 Here is a gist of the generated code 如果你没有安装 babel。
问题
rl.prompt 与 readline.clearLine 不兼容吗?怎么解决?
【问题讨论】: