Created
September 23, 2011 02:42
-
-
Save jay3sh/1236634 to your computer and use it in GitHub Desktop.
How to write interactive CLI utility in node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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