Search code examples
node.jskeypressprompt

How can I use keypress and prompt libraries same time?


I want to catch all key presses, but also, use prompt library.

var Prompt = require("prompt")
  , Keypress = require("keypress")
  ;

Prompt.start();
var schema = {
    properties: {
        name: {
            required: true
          , description: "What's your name?"
        }
    }
};

Prompt.get(schema, function (err, result) {
    console.log(err || result);
});

process.stdin.on("keypress", function (ch, key) {
    console.log(key);
    if (key && key.name === "c" && key.ctrl) {
        process.exit();
    }
});

The issue is that after prompt callback is called, keypress events are not triggered anymore.

Is there a solution/work around for this?


Solution

  • I found the following workaround:

    // Override get method
    var oldGet = Prompt.get;
    Prompt.get = function (schema, callback) {
        oldGet.call(this, schema, function () {
            process.stdin.setRawMode(true);
            process.stdin.resume();
            callback.apply(this, arguments);
        });
    };
    

    I used this in the cli-github project.