You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Inquirer.js中含fetch的校验函数导致重复提示的问题解决

问题原因与解决方案

问题根源

  1. 异步校验的状态干扰:你的校验函数是异步的(用了async/await),Inquirer处理异步校验时会自动显示加载动画(就是那个⠹),而你在校验函数里加的console.log会打乱终端的界面渲染逻辑,导致提示重复出现。
  2. 多余控制台输出:validateUsername里的console.log(input)和console.log(data.message)直接在终端打印内容,干扰了Inquirer的交互界面渲染,让提示被重复刷出。
  3. 未处理异常场景:当前代码没考虑fetch请求失败的情况(比如网络不通),这种情况会导致校验逻辑出错,进一步引发界面异常。
  4. 字段名重复bug:原代码中Twitter和Facebook的输入项name都设为twitter,会导致后一项输入覆盖前一项的结果。

修复后的代码

import * as fs from "fs";
import fetch from "node-fetch";
import inquirer from "inquirer";

const validateUsername = async function (input) {
  try {
    const response = await fetch(`https://api.github.com/users/${input}`);
    // 非200状态码直接判定用户不存在
    if (!response.ok) {
      return "用户不存在,请输入有效的GitHub用户名。";
    }
    return true;
  } catch (err) {
    return "网络请求失败,请检查网络连接后重试。";
  }
};

inquirer
  .prompt([
    {
      name: "projectName",
      message: "项目名称是什么?",
      type: "input",
    },
    {
      name: "projectDescription",
      message: "项目描述是什么?",
      type: "input",
    },
    {
      type: "input",
      name: "githubUser",
      message:
        "你的GitHub用户名是什么?(用于生成Shields徽章,获取代码大小、仓库大小、文件数量和许可证类型)",
      validate: validateUsername,
      // 可选:关闭异步校验时的加载动画,避免视觉混淆
      waitOnValidating: false
    },
    {
      name: "githubRepoName",
      message:
        "你的GitHub仓库名称是什么?(用于生成Shields徽章,获取代码大小、仓库大小、文件数量)",
      type: "input",
    },
    {
      name: "contribution",
      message: "请输入你的贡献号召及相关信息。",
      type: "input",
    },
    {
      type: "input",
      name: "licence",
      message: "项目使用哪种许可证?",
    },
    {
      type: "input",
      name: "twitter",
      message: "Twitter账号?直接回车跳过。",
    },
    {
      type: "input",
      name: "facebook",
      message: "Facebook账号?直接回车跳过。",
    },
  ])
  .then((answers) => {
    // 处理用户输入
  });

关键修复点

  • 移除所有干扰终端渲染的console.log,避免打乱Inquirer的界面逻辑。
  • 改用响应状态码判断用户是否存在,无需解析完整JSON,提升校验效率。
  • 增加try/catch捕获网络异常,给出友好错误提示。
  • 修复了社交账号输入项的name重复问题,避免输入结果被覆盖。
  • 可选配置waitOnValidating: false,关闭异步校验时的加载动画,消除状态切换带来的视觉混淆。

内容的提问来源于stack exchange,提问作者shau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 05:30:53