gpt4 book ai didi

node.js - 在 Node 中使用 readline prompt/setPrompt 时无法清除行

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:49 24 4
gpt4 key购买 nike

使用 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'?我希望游戏中的响应迅速,避免按下输入

我尝试过的:

  • 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)。 Here is a gist of the generated code如果你没有安装 babel。

问题

rl.prompt 是否与 readline.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 会很好。

关于node.js - 在 Node 中使用 readline prompt/setPrompt 时无法清除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37014419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com