Search code examples
node.jsstdinkeypressreadline

How can I prevent a key repeating in NodeJS


I am writing a command-line utility with NodeJS and I want to collect raw keyboard input from a user. However I want to prevent them from long-pressing a key and that key repeating until they release the key. Each key press should only return a single character, regardless of how long the key is pressed.

Suppose I have the following code:

const readline = require('readline')

readline.emitKeypressEvents(process.stdin)
process.stdin.setRawMode(true)

process.stdin.on('keypress', (str, key) => {
  process.stdout.write(str)
  // more code

  if (key.ctrl && key.name === 'c') {
    process.exit(0)
  }
})

How can I prevent key repeats?


Solution

  • Maybe you can store the value and set a timer to unlock if the same key is pressed. For example:

    const readline = require("readline");
    
    readline.emitKeypressEvents(process.stdin);
    process.stdin.setRawMode(true);
    
    let lastKey = "";
    let lastKeyTime = 0;
    
    process.stdin.on("keypress", (str, key) => {
        // Check same key with time 0.6 sec
        if (lastKey == key.sequence && new Date().getTime() - lastKeyTime < 600) {
            lastKeyTime = new Date().getTime();
            return;
        }
    
        // Print
        process.stdout.write(str);
    
        // Add data
        lastKey = key.sequence;
        lastKeyTime = new Date().getTime();
    
        if (key.ctrl && key.name === "c") {
            process.exit(0);
        }
    });