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)
});
Written by Vincent Voyer
Related protips
3 Responses
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/7635/44e4c29e4522a91f6c6ae8448f558a74.jpeg)
@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?
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/4809/6c8618df1a325d0fb9644ee221086fb7.jpeg)
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>
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/124573/none.jpg)
Here is a version using ES6 Promises: https://gist.github.com/a5c1f514babbb3309099