NodeJs – Simple console questionnaire

In this tutorial, I’ll show you how you can achieve a simple console apps that you’d like to pre-configure a set of question.

By refer to the tiny CLI example, it basically prompt the user for input and repeat over and over again until user input ^Z to terminate the program.

Screen Shot 2014-08-11 at 6.04.16 PM

 

Now we modified the program by setting up 3 question prompt for user and terminate whenever all question is answered.

// import library and defined interface
var rl = require("readline");
var interface = rl.createInterface(process.stdin, process.stdout, null);

// define variable
var questions = [  'Question 1) How was your day?', 
	           'Question 2) What color you like?', 
                   'Question 3) Do you have car?' ]
                   ,ctr = 0, qLength = questions.length;

// defined function
var questionnaire = function() {
    interface.setPrompt( questions[ctr] );
    interface.prompt();
}

// execute the questionnaire function
questionnaire();

// event listener from user input
interface.on('line', function(line) 
{
       switch(ctr) 
       {
          case 0: 
            console.log(line + ", Good to heard that!");
            ctr++;
            questionnaire();
            break;
          case 1:
            console.log(line + ", Okay, I know it now");
            ctr++;
            questionnaire();
            break;
          case 2:
            console.log(line + ", Awesome!");
            this.close();
            break;
     }
}).on('close', function() {
    return interface.close();
    process.stdin.destroy();
});
        

Example output:

Screen Shot 2014-08-11 at 6.13.06 PM

** Additionally, It seem like not make sense with looping technique simply because the blocking is something nodejs not encourage. So I’d use the callback function instead.

 

NodeJs – Simple console questionnaire

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.