To use this module, do require('readline')
.
Takes two streams and creates a readline interface. The completer
function is used for autocompletion. When given a substring, it returns [substr, completedStr]
. TODO: write some code to make sure I'm right.
createInterface
is commonly used with process.stdin
and
process.stdout
in order to accept user input:
var readline = require('readline'),
rl = readline.createInterface(process.stdin, process.stdout);
Sets the prompt, for example when you run node
on the command line, you see
>
, which is node's indicator.
TODO: look in readline's code and see what word it uses for the prefix to the
line.
Readies readline for input from the user, putting the current setPrompt
options on a new line, giving the user a new spot to write.
TODO: Write the above
function (line) {}
Emitted whenever the in
stream receives a \n
, usually received when the
user hits enter, or return. This is a good hook to listen user input.
Example of listening for line
:
rl.on('line', function (cmd) {
console.log('You just typed: '+cmd);
});
function () {}
Emitted whenever the in
stream receives a ^C
or ^D
, respectively known
as SIGINT
and EOT
. This is a good way to know the user is finished using
your program.
Example of listening for close
, and exiting the program afterward:
rl.on('close', function() {
console.log('goodbye!');
process.exit(0);
});
Here's an example of how to use all these together to craft a tiny command line interface:
var readline = require('readline'),
rl = readline.createInterface(process.stdin, process.stdout),
prefix = 'OHAI> ';
rl.on('line', function(line) {
switch(line.trim()) {
case 'hello':
console.log('world!');
break;
default:
console.log('Say what? I might have heard `' + line.trim() + '`');
break;
}
rl.setPrompt(prefix, prefix.length);
rl.prompt();
}).on('close', function() {
console.log('Have a great day!');
process.exit(0);
});
console.log(prefix + 'Good to see you. Try typing stuff.');
rl.setPrompt(prefix, prefix.length);
rl.prompt();
Take a look at this slightly more complicated example, and http-console for a real-life use case.