Node JS questions and answers application

Here we are creating a questions.js file in which we will declare an array of questions and user will be prompted to provide the answers. Then we will display the out on console.

To run the javascript file, please install nodejs and run node questions command.


//declare and initialize an array of questions

const questions = [
    "What is your name?",
    "what is your favourite programming language?"
];

//use node js process global object to write the questions

const ask = ( i = 0 ) => {
    process.stdout.write(`\n\n\n ${questions[i]} `);
    process.stdout.write(` > `);
}

//call ask function
ask();


const answers = [];

//use process stdin to accept user input
process.stdin.on("data", data => {

    answers.push(data.toString().trim());

   //check if all questions are answered 
    if ( answers.length < questions.length ) {
        ask(answers.length);
    } else {
        process.exit();
    }
});

//on process exit event, display the out to the console
process.on("exit", () =>{
    const [ name, language] = answers;
    console.log(`
        Thank you for your answers.
        Your name is ${name}.
        Your favourite programming language is ${language}.
    `);
});

Leave a Comment

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