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?如何解决这个问题?
我是这样解决的:
\n\nimport 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)\nRun Code Online (Sandbox Code Playgroud)\n\n但问题仍然存在,为什么不rl.prompt兼容readline.clearLine?
我猜这prompt与我在幕后的做法类似。一个resetPromptInput会很好。