0

我在让inquirer.js 在我正在处理的简单CLI 中顺利工作时遇到问题。首先,提示问题重复了几次,这需要修复。其次,我将代码编写为模块中的类,但不需要在此处包含代码使其成为模块,因此仅包含下面的类代码。在下面的代码中,我试图从inquirer.js 提示符中访问用户选择的选项,但我无法将用户选择的答案记录到控制台。我正在尝试在这里编写一个类,这样我就可以在需要inquirer.js 功能的任何时候实例化一个对象,并且只需更改某些属性来自定义提示。我还使用了几个额外的模块 Colors.js 和 Shell.js 我非常感谢一些知识渊博的程序员提供的任何帮助,感谢您的帮助:

到目前为止,这是我的代码:

    /* See Examples Below To Test This Class */
const inquirer = require('inquirer');
const sh = require('shelljs');
const colors = require('./colors');
const color = colors.color;

// class to instantiate an inquirer prompt
class PromptQue {
  constructor(pP) { // pP is an passed Object of params {key:value pairs}
    this.pP = pP;
    this.answer = undefined; // a class property to hold user's answer to prompt
    this.clearTerm = false; // set true if need to clear user window after prompt
    this.promptColor = color.tan; // assign a color to prompt question text from colors.js
    this.statusBar = new inquirer.ui.BottomBar();
    this.doStatusMsg = false; // set true if need to display status message
    this.statusColor = color.warning; // assign a color to status message text from colors.js
    this.statusMsg = undefined; // assign a status message
    // this.choicesColor = color.offwhite;

    // the switch below tests whether a normal Array
    // or an Assoc Array Object was passed as answer 'choices'
    switch(pP.hasOwnProperty('choices')) {
      case true:
        let testIfArray = Array.isArray(this.pP.choices);
        if(!testIfArray) { // if not Array convert 'choices' object to array
          this.pP.choices = this.GenArr(pP.choices);
        }
      case false:
        break;
    }

    this.updateParams(); // call to set colors/styles on color enabled params
  }

// ### !!! -----------------  DEBUG THIS!  ------------------------------ >>>

// ### !!! Prompt() Method: Can't Get The Answer Returned !! ------ ###
  // call Prompt() method to run the PromptQue instance
  Prompt() {
    return new Promise((resolve, reject) => {
      // doStatusMsg is set true, display status message
      this.checkStatusMsg();
      inquirer.prompt([
        this.pP // this is the Object Params passed to constructor
      ]).then((answer) => { // getting user's answer to prompt
        this.answer = answer[this.pP.name];
        return this.answer;
      }).catch((err) => {console.log(err)});
    })
    .then(() => this.clearStatus())
    .then(() => this.clear(this.clearTerm)); // if true : clear user window after prompt
  }

> ```
    // CONTINUING CODE :::::::::::
    // ### !!! -----------------  DEBUG THIS!  ------------------------------ >>>

      showData() {
        let keys = Object.keys(this.pP);
        keys.forEach((key) => {
          if(key === 'choices') {
            let arr = this.pP['choices'];
            let choicesStr = '';
            let cntr = 0;
            arr.forEach((val) => {
                if(cntr < this.pP['choices'].length) {
                  choicesStr += `${val}, `;
                } else {
                  choicesStr += `${val}`;
                }
                cntr++;
            });
            console.log(color.gray(`choices: ${choicesStr}`));
          } else {
            console.log(color.gray(`${key}: ${this.pP[key]}`));
          }
        });
        console.log(color.gray(`clearTerm: ${this.clearTerm}`));
        let C = this.promptColor('#COLOR');
        console.log(color.gray(`promptColor: ${C}`));
        console.log(color.gray(`statusMsg: ${this.statusMsg}`));
        console.log(color.gray(`doStatusMsg ${this.doStatusMsg}`));
        C = this.statusColor('#COLOR');
        console.log(color.gray(`statusColor: ${C}`));
      }

      // function to convert object into regular array
      GenArr(arr) {
        let regArr = [];
        for(var key in arr) {
          var value = arr[key];
          regArr.push(value);
        }
        return regArr;
      }

      // rebuilds colored enabled params with specified colors/styles
      updateParams() {
        let keys = Object.keys(this.pP);
        keys.forEach((key) => {
          switch (key) {
            case 'message':
              this.pP['message'] = this.promptColor(this.pP['message']);
              break;
          }
        });

        if(this.statusMsg) {
          this.statusMsg = this.statusColor(this.statusMsg);
        }
      }

      // displays a new message (msg) in the Status Bar
      checkStatusMsg() {
        if(this.doStatusMsg) {
          let msg = `${this.statusColor.bold(this.statusMsg)}\n`;
          this.setStatus(msg);
        }
      }

      // Set a status message for the prompt
      setStatus(msg) {
        this.statusBar.updateBottomBar(msg);
        // return msg;
      }

      // Clears the Status Bar's Field
      clearStatus() {this.statusBar.updateBottomBar('')}

      // Method to get user's selected choice for this prompt
      getAnswer() {
        return this.answer;
      }

      // console.log the user's selected choice for this prompt, mainly for debugging
      logAnswer() {
        if(this.answer !== undefined) {
          console.log(color.ltgray.italic.bold(`User Choice: ${this.answer}`));
        }
      }

      // function to clear user terminal screen
      clear(bool) {
        if(bool) {
          sh.exec('clear');
        }
      }
    }

    /////***********  CODE-END  ***********/////



    //----------- Test Code Below ---------------------

    /////****  TESTING ABOVE CODE  ****/////

    const sizeList = {0:'Jumbo',1:'Large',2:'Standard',3:'Medium',4:'Small',5:'Micro'};
    // create an object to pass to new instance

    // SETTING UP PROMPT HERE
    let cPromptData = {
      type: 'list',
      message: color.tan('What size Pizza do you need?'),
      name: 'pizza',
      choices: sizeList
    };
    let cPrompt = new PromptQue(cPromptData);
    cPrompt.statusMsg = 'Pizza! I Love Pizza!';
    cPrompt.doStatusMsg = true;

    // CALLING PROMPT
    cPrompt.Prompt();


    //-----------------------------------------------------

    const myPromise = new Promise((resolve,reject) => {
      cPrompt.Prompt();
    }).then(() => console.log(`Selected: ${cPrompt.answer}`));
    myPromise.then(() => console.log(`Selected: ${cPrompt.answer}`));

    // TRYING TO ASSIGN USER'S ANSWER HERE AND LOG TO CONSOLE! *NOT WORKING
    let ans = cPrompt.Prompt();
    console.log(`Selected: ${ans}`);

这是颜色模块代码:

const __MODULEINFO__ = {
    package: 'lib',
    name: 'colors',
    sub: 'cli colors & styles',
    context: 'Colors & Styles module that utilizes Chalk JS',
    version: '1.0.0',
    dependencies: ['chalk.js'],
}
exports.MODULEINFO = __MODULEINFO__;
/*//// Module Introspection Stuff - End ////*/


/////***********  CODE-START  ***********/////

const chalk = require('chalk');

/* COLOR/STYLES INITIALIZE */
// white
const white = chalk.white;
// offwhite
const offwhite = chalk.hex('#f2f2d9');
// blue
const blue = chalk.hex('#0033ff');
// tan
const tan = chalk.hex('#cca26c');
// green
const green = chalk.hex('#009900');
// ltgray
const ltgray = chalk.hex('#d9d9d9');
// gray
const gray = chalk.hex('#808080');
// error
const alert = chalk.hex('#ff0000');
// warning
const warning = chalk.hex('#ff5c00');

//* ** COLOR-STYLES ** *//
const color = {
  white: white,
  blue: blue,
  tan: tan,
  green: green,
  ltgray: ltgray,
  gray: gray,
  alert: alert,
  warning: warning,
}

exports.color = color;


/////***********  CODE-END  ***********/////

/* *****  DEV NOTES  ***** /*

// NEEDS MORE WORK!

// add any of these colors/styles or add custom ones:

// turqoise
turq: chalk.hex('#02B388');
bgturq: chalk.whiteBright.bgHex('#00624F');
// info: blue
info: chalk.hex('#0092ff');
bginfo: chalk.white.bgHex('#285095');
// warning: orange
warn: chalk.hex('#ff8700');
bgwarn: chalk.whiteBright.bgHex('#ce6d00');
// error: red
error: chalk.hex('#ff0000');
bgerror: chalk.whiteBright.bgHex('#eb0000');
// dim: grey
grey: chalk.hex('#a1a1a1');
bggrey: chalk.hex('#a1a1a1').bgHex('#2d2d2d');
// dim: tan
tan: tan = chalk.hex('#cca26c');
bgtan: chalk.hex('#cca26c').bgHex('#3b2b1c');
// yellow
yellow: chalk.hex('#fff500');
bgyellow: chalk.whiteBright.bgHex('#e6c200');
// dark
dark: chalk.hex('#000000');
bgdark: chalk.hex('#000000').bgHex('#747474');
darkbold: chalk.hex('#000000').bold;
bgdarkbold: chalk.hex('#000000').bgHex('#747474').bold;
// red bold
redbold: chalk.red.bold;
// red italic
reditalic: chalk.red.italic;
// red underline
redul: chalk.red.underline;
// red strike
redstrike: chalk.red.strikethrough;
// red dim
reddim: chalk.red.dim;
// blue
blue: chalk.blue;
// blue bold
bluebold: chalk.blue.bold;
// blue dim
bluedim: chalk.blue.dim;
// blue italic
blueitalic: chalk.blue.italic;
// green
green: chalk.green;
// green bold
greenbold: chalk.green.bold;
// green dim
greendim: chalk.green.dim;
// green italic
greenitalic: chalk.green.italic;

// TEXT-STYLES //

// bold text
bold: chalk.bold;
// dim text
dim: chalk.dim;
// italic text
italic: chalk.italic;
// underline
ul: chalk.underline;
// inverse - invert bg and fg
invert: chalk.inverse;
// strikethrough
strike: chalk.strikethrough;
// bold italic
bolditalic: chalk.bold.italic;
// bold dim
bolddim: chalk.bold.dim;
// dim italic
dimitalic: chalk.dim.italic;
// dim underline
dimul: chalk.dim.underline;
// italic underline
italicul: chalk.italic.underline;
;-----

*/
4

1 回答 1

0
/* Create project directory called 'inquirtest-cli' and CD to it then/n in terminal run 'npm init' overwrite package.json created with the/n below package.json, then create a sub-directory called bin in your/n project directory, then create a main file 'inquirtest.js', then in /nproject directory run 'sudo npm link' which will enable you to just type/n 'inq' in terminal at any directory and it will run the main code. /npackage.json content: */

// package.json

{
  "name": "inquirtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "bin": {
    "inq": "./bin/inquirtest.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "robogenus",
  "license": "MIT",
  "dependencies": {
    "colors": "^1.4.0",
    "commander": "^5.1.0",
    "inquirer": "^7.1.0"
  }
}

// inquirtest.js

#!/usr/bin/env node

const inquirer = require('inquirer');
const colors = require('colors');

const doPrompts = () => {
        const ques = [
                {
                        type: 'input',
                        name: 'fullname',
                        message: 'What is your name? '.yellow
                },
                {
                        type: 'list',
                        name: 'gender',
                        message: 'Select your gender: '.yellow,
                        choices: ['Male', 'Female']
                }
        ];

        return inquirer.prompt(ques);
};

const run = async () => {
        const answers = await doPrompts();
        const { fullname, gender } = answers;

        console.log(`Hi there ${fullname}! Hmm?... So you are ${gender} type gender.`);
};
于 2020-04-29T22:01:40.693 回答