Thursday, September 22, 2011

How to write interactive CLI utility in node.js

Node.js is mainly a server development framework - accepting requests and responding to them over network. But sometimes need arises to write a CLI utility using node.js. The asynchronous nature of node.js can make it difficult to write a simple CLI utility that will ask series of questions and accept answers from the user. Recently I ran into such situation, here is how I wrote one. (Learnt about the ask function from this post)
gist

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();
view raw node-cli.js hosted with ❤ by GitHub