0

I want to get user input from user. I have created a function to do that by taking the code from node.js documentation. But I cannot receive multiple user inputs. How can I do that? This is the code so far.

function getUserInput() {
        rl.question('Please input a letter: ', (answer) => {
        console.log('Letter entered: ${answer}');
        rl.close();
        }); 
    }

//getUserInput();

var k=0; 
while ( k < 3 ){
        getUserInput();
        k++;
    } 

I expect to take for example 3 user inputs. I want to take user input. With the code above I can only take only ONE user Input. I thought adding the function into a loop so it could work. I am looking for any modification into my code so It can work and so I can take more than one user input.

klevisx
  • 175
  • 1
  • 2
  • 12
  • Hey! Welcome to StackOverflow! Please check this one: https://codereview.stackexchange.com/questions/134048/flattening-multiple-nested-node-readline-questions – Zooly Jan 25 '19 at 16:24
  • There isn't enough information provided to get a clear understanding of what you're trying to achieve. Could you provide more information? – kemicofa ghost Jan 25 '19 at 16:30
  • Let me write it here and I will add to the description. I want to take user input. With the code above I can only take only ONE user Input. I thought adding the function into a loop so it could work. I am looking for any modification into my code so It can work and so I can take more than one user input. – klevisx Jan 25 '19 at 16:36
  • Potential duplicate: https://stackoverflow.com/questions/8128578/reading-value-from-console-interactively – k0pernikus Jan 25 '19 at 16:42
  • It is different. I ve seen that link – klevisx Jan 25 '19 at 16:45

3 Answers3

1

Inquirer is probably what you're looking for, assuming that you're trying to get user input on the command line.

Description taken from the repo itself:

Inquirer.js strives to be an easily embeddable and beautiful command line interface for Node.js (and perhaps the "CLI Xanadu").

Inquirer.js should ease the process of

  • providing error feedback
  • asking questions
  • parsing input
  • validating answers
  • managing hierarchical prompts

Also, here's an example on how to use it:

const inquirer = require('inquirer');

const questions = [
  {
    type: 'input',
    name: 'first_name',
    message: "What's your first name"
  }, {
    type: 'input',
    name: 'last_name',
    message: "What's your last name",
    default: function() {
      return 'Doe';
    }
  }
];

inquirer.prompt(questions).then(answers => {
  console.log(JSON.stringify(answers, null, '  '));
});

Cheers.

Community
  • 1
  • 1
chrisg86
  • 11,548
  • 2
  • 16
  • 30
  • I am checking it rn. Isnt there any easier way to achive this with a loop like I started doing ? Thanks :) – klevisx Jan 25 '19 at 16:26
  • 1
    As it currently stands, this looks more like a comment than an answer. Providing more information about what "inquirer" does would be helpful to the OP rather than providing just an external link. An example on how it works would also be beneficial. – kemicofa ghost Jan 25 '19 at 16:27
  • yea actually that's what I am looking for. Maybe any modification on my code would be great. I have been dealing with it for hours And I cant figure it out what the problem is. Thanks – klevisx Jan 25 '19 at 16:31
0

This appears to be using something like the promises API.

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
}); 


function getUserInput(n) {
    rl.question('Please input a letter: ', (answer) => {
        console.log(`Letter entered: ${answer}`);
        if (n < 3) {
            getUserInput(n+1);
        } else {
            rl.close();
        }
    }); 
}

getUserInput(1);

When I run it, this happens:

$ node getinput.js
Please input a letter: a
Letter entered: a
Please input a letter: b
Letter entered: b
Please input a letter: c
Letter entered: c
Ben Stern
  • 306
  • 1
  • 9
  • Your provided code is not working. It is the same thing. :( – klevisx Jan 25 '19 at 16:38
  • This is working for me just fine. Originally, it issued 4 prompts instead of 3, but I fixed that by calling `getUserInput` with a 1 as suggested above. – Ben Stern Jan 27 '19 at 22:18
0

I think the problem is that rl.question waits for an input before proceeding but the while loop doesn't. Here's a simple node cli that does what you're after, I think. Just save this code in a file named index.js and go to the directory and type: node index.js

 // Dependencies
 var readline = require('readline');

 var cli = {};

 // Init function
 cli.init = function(){
   // Send the start message to the console in magenta
   console.log('\x1b[35m%s\x1b[0m',"The CLI is running");

   // Start the interface
   var _interface = readline.createInterface({
     input: process.stdin,
     output : process.stdout,
     prompt : '>'
   });

   var arrayOfInputs = [];
   var k = 0;
   var max = 3;
   cli.getUserInput = function(){
     _interface.question("Ask Something? ", function(str){
       k++;
      arrayOfInputs.push(str);
      if(k < max){
        cli.getUserInput();
      } else {
        console.log(...arrayOfInputs);
      }
    });
   };

   cli.getUserInput();

 };

 cli.init();
T. Stoddard
  • 111
  • 4
  • 1
    I think that Ben Stern's answer will work also if you just change `getUserInput(n+1);` to `getUserInput(++n);`. Also, change the initial call to `getUserInput(0)` to `getUserInput(1)` or you'll get 4 inputs because rl.question get's called before n is tested. – T. Stoddard Jan 25 '19 at 18:46
  • okay thanks. let me check this. (edit) It looks like its working. thanksss I will keep you updated for the stage of the program ;) – klevisx Jan 26 '19 at 15:50
  • Why did this work for the OP and mine didn't? I agree about the off-by-one, but this is functionally equivalent otherwise. – Ben Stern Jan 27 '19 at 22:24
  • You're right, Ben. Your code does work. I don't know why it didn't work for the OP except that it ran 4 times, which might have led to the incorrect assumption that it wasn't working right. I don't think I tried your code before I wrote mine. I just looked at it afterwards and tried to point out to the OP that your approach was a good one. – T. Stoddard Jan 28 '19 at 00:15