Last Updated: December 13, 2017
·
17.68K
· vvo

Simple Node.js prompt

If you wanna ask a one-line question to your user using node.js and stdin, do:

var rl = require('readline');

module.exports = function ask(question, callback) {
  var r = rl.createInterface({
    input: process.stdin,
    output: process.stdout});
  r.question(question + '\n', function(answer) {
    r.close();
    callback(null, answer);
  });
}

ask('Did you find this usefull?', function(answer) {
  console.log(answer)
});

3 Responses
Add your response

@turg0n Hey hi. I tried commander.js before diving into node's readline functions.

It turned out commander.js was buggy. When prompting, ̀return ̀ would not trigger end of prompt, needed to press ̀return ̀ twice.

All I needed was a simple prompt function. Did not want to debug a library that seemed not so up to date based on new node readline library. So made my simple function and voilà!

Now thinking to build my own simple node-input library that would prompt/confirm/choose only. No option parsing etc as commander.js do. There are already a lot of modules for that.

What do you think?

over 1 year ago ·

I really liked your method, but I am using promises so I edited it slightly, this is my edited version that uses q library for promises

var ask = function(question) {
    var deferred = q.defer();

var r = rl.createInterface({
    input: process.stdin,
    output: process.stdout
});

r.question(question + '\n', function(answer) {
    r.close();
    deferred.resolve(answer);
});


return deferred.promise;
};</code></pre>
over 1 year ago ·

Here is a version using ES6 Promises: https://gist.github.com/a5c1f514babbb3309099

over 1 year ago ·