Search code examples
node.jscommand-linemodulewizardreadline

How to provide a default answer to readline in node.js


js in order to create a command line wizard.

The wizard asks some question to the user using the rl.question(query, callback) method.

The problem is that I want to make the question and to provide a default answer in order to let the user able to press enter to confirm the default answer, to edit the default answer or to cancel the default answer and press enter to skip the question.

Something like this:

What's your favorite color? Red_

if the user press enter: the answer will be Red if the user change Red to Green: the answer will be Green if the user cancel Red and press enter: the answer will be "" and the wizard will skip to the next question.

Do You know how to make something like this with Node.js?


Solution

  • You can use rl.write after rl.question call to add default value to tty.

    Example:

    var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);
    
    rl.question('What is your favorite food? ', function(answer) {
            console.log('Oh, so your favorite food is ' + answer);
    });
    rl.write('Pizza');