Skip to content

Instantly share code, notes, and snippets.

@SBoudrias
Created May 13, 2013 20:56
Show Gist options
  • Save SBoudrias/5571454 to your computer and use it in GitHub Desktop.
Save SBoudrias/5571454 to your computer and use it in GitHub Desktop.
Node.js Readline and CLI keypress example
var readline = require('readline'),
_ = require('lodash'),
charm = require('charm')(process.stdout),
rl = readline.createInterface(process.stdin, process.stdout);
var selected = 0;
var choices = [
"foo",
"bar",
"javascript",
"bleurp"
];
function renderChoices() {
choices.forEach(function( choice, i ) {
charm.foreground("cyan");
charm.write("[" + (i === selected ? "X" : " ") + "] ");
(i !== selected) && charm.foreground("white");
charm.write(choice + "\r\n");
charm.foreground("white");
});
}
process.stdin.on('keypress', function(s, key) {
if( key.name === "up" && (selected - 1) >= 0 ) {
selected--;
} else if( key.name === "down" && (selected + 1) < choices.length ){
selected++;
} else {
return; // don't render if nothing changed
}
charm.erase("line");
choices.forEach(function() {
charm.up(1);
charm.erase("line");
});
renderChoices();
});
renderChoices();
rl.on('line', function(line) {
charm.write("You choosed: " + choices[selected] + "\r\n");
process.exit(0);
}).on('close', function() {
console.log('Have a great day!');
rl.close();
process.exit(0);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment