How to terminate npm inquirer prompt and return control to main menu/function
Asked Answered
H

1

7

I keep running into an issue with the inquirer npm package and cant find a solution anywhere. I am trying to allow a user to exit the inquirer prompt in a function at any point and return to the main menu. However, it seems this is causing multiple instances of the inquirer prompt to remain active causing this error:

(node:9756) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners added. Use emitter.setMaxListeners() to increase limit

and also causing the inquirer prompt in the specific function to begin displaying the same prompt multiple times. I attached an image of the behavior after trying to use the function a several times. Prompt Bug

I have tried increasing the maximum number of event listeners which stopped the memory leak error but the inquirer prompt bug was unaffected.

inquirer.prompt([
        {
            name: 'itemid',
            type: 'input',
            message: 'Please enter the product id. (type "exit" to return to main menu)',
            validate(answer) {

                //validates the id provided exists in the database. If exit is entered, returns to main().
                var valid = false;
                var exit = answer.toLowerCase();
                id = parseInt(answer);

                if (exit == "exit") {
                    return main();
                }

                for (var j = 0; j < idCheckArray.length; j++) {

                    if (answer == idCheckArray[j]) {

                        valid = true;

                    } else {
                    }
                }

                if (valid === true && exit != "exit") {

                    return (true);

                } else {

                    return ("Item ID does not exist. Please enter a valid ID.");
                }
            }
        },

I believe the cause is that by returning and calling main from within the inquirer validate function, inquirer does not call its build in end function and as a result every time this action is performed the event listeners created by inquirer are not removed.

Any help with how to address this is greatly appreciated, Thanks.

Haulm answered 6/8, 2018 at 18:6 Comment(1)
Were you able to find a solution for this?Camm
C
2

What I do is create a function called WantToExit

const WantToExit = () =>
  inquirer
    .prompt([
      {
        name: "moreQuery",
        type: "confirm",
        message: "Want to do anything else?",
      },
    ])
    .then((answer) => {
      if (answer.moreQuery) return init();
    });

Note that init is the main function where I run the first inquirer.prompt e.g.

function init() {
  inquirer.prompt(initialQuestionsList).then(async (answer) => {
    console.log(answer);
    })

Copter answered 23/5, 2021 at 3:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.