【问题标题】:javascript readline: when the user inputs a letter i want to exit right away with that letterjavascript readline:当用户输入一个字母时,我想立即退出该字母
【发布时间】:2021-07-23 04:16:13
【问题描述】:

我正在使用 Nodejs 的 readline 模块,我想要做的是当用户输入一个字母时。他们输入的键我想立即返回该键(字母),就像按下回车键一样,但仍然是他们按下的键(字母)。

在下面的代码中,我有提示要求用户输入 w、a、s 或 d 所以我希望这 4 个键在单击时立即返回,如果他们输入任何其他键,终端会忽略它根本不显示我该怎么做?

const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
/// the function is below
function userInput(input) {
  input = readline.question('Please move\n (w for up)\n (a for left)\n (s for down)\n (d for right)', 
  theMove => {
  console.log(`Nice move ${theMove}!`);
  readline.close();
});
userInput();

【问题讨论】:

    标签: javascript node.js module node-modules readline


    【解决方案1】:

    你可以这样做:

    
    const readline = require('readline').createInterface({
       input: process.stdin,
       output: process.stdout
       });
       /// the function is below
       function userInput() {
       const allowedKeys = 'wasd';
         input = readline.question('Please move\n (w for up)\n (a for left)\n (s for down)\n (d for right)', 
         theMove => {
            if (allowedKeys.includes(theMove)) {
             console.log(`Nice move ${theMove}!`);
             readline.close();
            }
            else {
             userInput();
             console.log('\n');
             console.log(`Nice move ${theMove}!`);
            }
       });
    }
    userInput();
    

    如果用户按下了允许之外的任何键,它将再次调用 userInput。

    这是来自 Node.js readline 文档:

    每当输入流接收到一个 行尾输入(\n、\r 或 \r\n)。这通常发生在用户 按 Enter 或 Return。

    所以,这就是它的工作原理。它将在收到行尾输入时调用调用,否则继续等待输入。检查here

    改为使用keypress 从用户那里获取输入,如下所示:

    var keypress = require('keypress')
      , tty = require('tty');
    
    // make `process.stdin` begin emitting "keypress" events
    keypress(process.stdin);
    
    // listen for the "keypress" event
    process.stdin.on('keypress', function (ch, key) {
       
      console.log('got "keypress"', key.name);
      
      const allowedKeys = 'wasd';
    
      if (allowedKeys.includes(key.name)) {
        process.exit();
      }
    });
    
    if (typeof process.stdin.setRawMode == 'function') {
      process.stdin.setRawMode(true);
    } else {
      tty.setRawMode(true);
    }
    process.stdin.resume();
    

    查看this了解更多详情。

    【讨论】:

    • 我已经用 switch 语句做到了,但我希望函数在按下时退出,基本上当他们按下'a'时我希望它立即被执行并且他们不必基本上按下回车键和然后当他们按下任何其他字母时,我什至不希望它们被打印或显示,因此它们被完全删除。希望这是有道理的
    • 您应该检查 readline 的工作,因为首先了解任何模块的工作很重要,然后再期待它的 o/p。如果您已经完成了与 switch 语句一起使用的操作,那就太好了。
    • 这有帮助还是您还有问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2016-12-14
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    相关资源
    最近更新 更多