Inquirer 与 prompts
交互式 CLI 输入。
25 分钟
Inquirer 与 prompts
非交互脚本用 flag 即可(nva-cli);面向人的向导 需要列表选择、确认、密码输入——Inquirer 与 prompts 是 Node CLI 常用方案。
学习目标
- 用 prompts 实现 confirm、select、text 交互
- 区分「CI 无 TTY」与本地交互降级策略
- 与 nva-errors 的用户错误提示配合
prompts 快速上手
import prompts from "prompts";
const answers = await prompts([
{
type: "text",
name: "table",
message: "PostgreSQL 表名",
validate: (v) => (v ? true : "不能为空"),
},
{
type: "confirm",
name: "dryRun",
message: "仅预览不写库?",
initial: true,
},
]);
if (!answers.table) process.exit(2); // 用户 Ctrl+C
轻量、Promise 友好;适合 nva-practice 的 import 向导。
Inquirer(经典栈)
import inquirer from "inquirer";
const { driver } = await inquirer.prompt([
{
type: "list",
name: "driver",
message: "数据源",
choices: ["postgres", "mongodb"],
},
]);
生态大、插件多;新项目可优先 prompts(体积小),团队已有 Inquirer 则保持一致。
CI 与 non-TTY
const isTTY = process.stdin.isTTY && process.stdout.isTTY;
if (!isTTY) {
// 必须从 env 或 argv 读取,禁止 hang 在 prompt
const table = process.env.IMPORT_TABLE;
if (!table) throw new UserError("非交互模式需设置 IMPORT_TABLE");
}
GitHub Actions 跑 CLI 时 永远提供 flag/env,交互仅本地开发——与 testing-essentials CI 场景一致。
选型对照
| 库 | 特点 |
|---|---|
| prompts | 小、现代、默认 ESM |
| inquirer | 成熟、插件多 |
| @clack/prompts | 美观 spinner、步骤 UI |
框架层无对应物;Nest 管理端用 HTTP 表单,CLI 工具仍用本课库。
与数据库 track 衔接
交互选择 postgres 时,后续连接串读取 DATABASE_URL(见 pg-install);选 mongodb 则读 MONGODB_URI(mongo-install)。——用 env 或 ()。