2

我正在制作一个自定义 CLI,所以我写了一个代码

#!/usr/bin/env node

var { program } = require("commander");
var { prompt } = require("inquirer");
const Science = require("./Science");
program.version("0.0.1");

// questions
const questions = [
  {
    type: "list",
    name: "subjectType",
    message: " Select export Source ",
    default: false,
    choices: [
      "Science",
      "Maths",
      "English",
      "Exit",
    ],
  },
];

function startQuery() {
  program
    .command("run")
    .alias("r")
    .description("Subject")
    .action(() => {
      prompt(questions).then((answers) => {
        if (answers.subjectType === "Science") {
          Science();
        } else if (answers.subjectType === "Maths") {
          // Maths();
        } else if (answers.subjectType === "Exit") {
          wantToExit();
        }
      });
    });
}

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

program.parse(process.argv);

因此,当我在控制台中键入 Subject run 时,它不会运行我的 cli,但是当我删除 startQuery 函数时,它会执行程序,我不知道它为什么会这样

通过删除函数 startQuery() 运行

program
    .command("run")
    .alias("r")
    .description("Subject")
    .action(() => {
      prompt(questions).then((answers) => {
        if (answers.subjectType === "Science") {
          Science();
        } else if (answers.subjectType === "Maths") {
          // Maths();
        } else if (answers.subjectType === "Exit") {
          wantToExit();
        }
      });
    });

然后在控制台中我写 Subject 正确运行它的 Execute 但是如果我这样做它不会执行程序

function startQuery() {
  program
    .command("run")
    .alias("r")
    .description("Subject")
    .action(() => {
      prompt(questions).then((answers) => {
        if (answers.subjectType === "Science") {
          Science();
        } else if (answers.subjectType === "Maths") {
          // Maths();
        } else if (answers.subjectType === "Exit") {
          wantToExit();
        }
      });
    });
}

因为我在 wantToExit 函数中需要这个 startQuery 函数,所以如果用户想继续,我可以再次使用它

4

0 回答 0