【问题标题】:Unable to clear line when using readline prompt / setPrompt in Node在 Node 中使用 readline prompt / setPrompt 时无法清除行
【发布时间】: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.promptreadline.clearLine 不兼容吗?怎么解决?

【问题讨论】:

    标签: node.js console prompt


    【解决方案1】:

    我是这样解决的:

    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 会很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-07
      • 2018-06-12
      • 2010-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      相关资源
      最近更新 更多