Skip to content

Instantly share code, notes, and snippets.

@jay3sh
Created September 23, 2011 02:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jay3sh/1236634 to your computer and use it in GitHub Desktop.
Save jay3sh/1236634 to your computer and use it in GitHub Desktop.
How to write interactive CLI utility in node.js
var questions = [
{ id:'fname', text:'First Name', answerType:'str' },
{ id:'lname', text:'Last Name', answerType:'str' },
{ id:'age', text:'Age', answerType:'int' },
{ id:'weight', text:'Weight', answerType:'float' }
]
function ask(question, callback) {
var stdin = process.stdin, stdout = process.stdout;
stdin.resume();
stdout.write(question + ": ");
stdin.once('data', function(data) {
data = data.toString().trim();
callback(data);
});
}
function process_answers(answers) {
console.log(answers);
}
function main() {
var i=0, l=questions.length, answers={};
var process_val = function (val) {
if(question.answerType == 'int') {
answers[question.id] = parseInt(val, 10);
} else if(question.answerType == 'float') {
answers[question.id] = parseFloat(val);
} else {
answers[question.id] = val;
}
if(i<l-1) {
question = questions[++i];
ask(question.text, process_val);
} else {
process_answers(answers)
}
};
var question = questions[i];
ask(question.text, process_val);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment