node-choice
v1.1.3
Published
Node-Choice is a lightweight command-line interaction tool that supports both selection mode (choosing from predefined options) and input mode (free-form user input). It simplifies the implementation of command-line interactions and is suitable for variou
Maintainers
Readme
Node-Choice
Node-Choice 是一个轻量级的命令行交互工具,支持 选择模式(从预定义选项中选择)和 输入模式(自由输入)。它简化了在 Node.js 项目中实现交互式提示的过程,并支持多语言。
功能特性
选择模式:
- 支持用户从预定义选项中选择。
- 提供默认选项并验证用户输入。
- 使用清晰的标记(
→)显示默认选项。
输入模式:
- 当未提供选项时,切换到自由输入模式,允许用户输入任意内容。
- 支持默认值,若用户未输入内容,则使用默认值。
多语言支持:
- 内置英文(
en)和中文(zh)语言包。 - 可轻松扩展以支持其他语言。
- 内置英文(
兼容性:
- 同时支持 ESM (
import) 和 CommonJS (require) 模块格式。
- 同时支持 ESM (
TypeScript 支持:
- 完全使用 TypeScript 实现,确保类型安全并提升开发者体验。
递归输入验证:
- 若用户输入无效选项,自动重新提示。
安装
通过 npm 安装:
npm install node-choice使用方法
选择模式
使用 import (ESM)
import { choice } from 'node-choice';
// 带预定义选项的选择模式
const result = await choice("What is your favorite color?", ["Red", "Green", "Blue"], 1, 'en');
console.log(`Selected: Index ${result.index}, Value: ${result.value}`);使用 require (CommonJS)
const { choice } = require('node-choice');
// 带预定义选项的选择模式
(async () => {
const result = await choice("请选择一种颜色?", ["红色", "绿色", "蓝色"], 1, 'zh');
console.log(`选择结果: 索引 ${result.index},值为: ${result.value}`);
})();示例输出
What is your favorite color?
1. Red
→ 2. Green
3. Blue
Enter option number (default: 2):
Selected: Index 1, Value: Green输入模式
使用 import (ESM)
import { choice } from 'node-choice';
// 输入模式
const result = await choice("Please enter your email:", [], "[email protected]", 'en');
console.log(`Input Result: ${result.value}`);使用 require (CommonJS)
const { choice } = require('node-choice');
// 输入模式
(async () => {
const result = await choice("请输入备注信息:", [], "无备注", 'zh');
console.log(`输入结果: ${result.value}`);
})();示例输出
Please enter your email:
(default: [email protected]): [email protected]
Input Result: [email protected]API 参考
choice(question, choices, selected, language)
参数:
question:
string
显示给用户的问题。choices:
string[](可选,默认为空数组)
预定义选项数组。如果为空,则切换到输入模式。selected:
number | string(可选,默认为0)
默认选中的选项索引(选择模式)或默认值(输入模式)。language:
'en' | 'zh'(可选,默认为'en')
提示信息的语言。支持以下值:'en': 英文'zh': 中文
返回值:
- 返回一个
Promise,解析为对象{ index: number, value: string }:- index: 选中选项的索引(输入模式下为
-1)。 - value: 选中选项或用户输入的值。
- index: 选中选项的索引(输入模式下为
注意事项
默认值处理:
- 在输入模式下,如果用户未提供输入且存在默认值,则返回默认值。
- 如果用户未提供输入且无默认值,则返回空字符串。
语言扩展:
- 若要支持更多语言,可在
messages对象中添加新的语言包。例如:const messages = { en: { /* 英文语言包 */ }, zh: { /* 中文语言包 */ }, fr: { /* 法语语言包 */ }, };
- 若要支持更多语言,可在
错误处理:
- 工具会自动检测无效输入并重新提示用户,无需额外处理。
贡献
欢迎提交 Pull Request 或 Issue!如果您发现任何问题或希望添加新功能,请随时联系我们。
许可证
本项目采用 MIT 许可证。
