Search code examples
javascriptnode.jsprompt

Is there a way to make a loop in prompt?


I am experimenting with the npm package, prompt, and would like to find out something.

Basically, I have this code:

prompt.start();
      
        prompt.get(['Age'], function (err, result) {
          if (err) return;

          console.log(result);

        })

The code is supposed to ask a question (Age) in the cmd prompt, and the user can answer it through the cmd prompt. It works fine, however once the user enters in their age, the prompt logs the result, and exits the process. I would like for the prompt to ask the question again every time AFTER the question is answered, instead of exiting the process. So, the console would look like this,

prompt: Age:  70                                                                                                                                     
prompt: 70
prompt: Age:

Is there any way to do this?


Solution

  • You can use the call signature of prompt.get which returns a promise and then await it inside a classic while loop. From the documentation:

    If no callback is passed to prompt.get(schema), then it returns a Promise, so you can also write:

    const {username, email} = await prompt.get(['username', 'email']);
    

    Here's an example module:

    example.mjs:

    import prompt from 'prompt';
    
    prompt.start();
    
    while (true) {
      try {
        const result = await prompt.get(['Age']);
        // Break out of the loop if "STOP!" is typed
        if (result.Age === 'STOP!') break;
        console.log(result);
      }
      catch (ex) {
        // handle exception
      }
    }
    
    console.log('Done');
    
    

    Running the program in the terminal:

    % node --version
    v18.12.1
    
    % node example.mjs
    prompt: Age:  10
    { Age: '10' }
    prompt: Age:  20
    { Age: '20' }
    prompt: Age:  30
    { Age: '30' }
    prompt: Age:  etc
    { Age: 'etc' }
    prompt: Age:  STOP!
    Done