引言
REPL 是 R(read)、E(evaluate)祝懂、P(print)顽耳、L(loop) 的縮寫坠敷,稱為交互式命令行妙同,是程序用來讀取用戶的輸入的方式。比如在 C 語言中調(diào)用<stdio.h>
中的 scanf
函數(shù)收集用戶輸入的數(shù)據(jù)膝迎。在執(zhí)行 npm init
時粥帚,也會出現(xiàn) REPL 收集創(chuàng)建 npm 包時所需的信息。
再比如:我們在使用 @vue-cli
腳手架創(chuàng)建項目時限次,敲下vue create my-app
命令后芒涡,會彈出配置選擇交互菜單:
Vue CLI v4.5.8
┌──────────────────────────────────────────┐
│ │
│ New version available 4.5.8 → 4.5.10 │
│ Run npm i -g @vue/cli to update! │
│ │
└──────────────────────────────────────────┘
? Please pick a preset: (Use arrow keys)
Default ([Vue 2] babel, eslint)
Default (Vue 3 Preview) ([Vue 3] babel, eslint)
Manually select features
? Please pick a preset: Manually select features
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)
(*) createChoice Vue version
(*) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
>( ) Router
( ) Vuex
( ) CSS Pre-processors
(*) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
這種便捷友好的 REPL 拓展工具,外形美觀掂恕、功能強(qiáng)大拖陆,而實現(xiàn)起來也非常簡單。下面就開始介紹一款 node 的 repl 工具:prompts
Prompts 介紹和使用
Lightweight, beautiful and user-friendly interactive prompts
輕量懊亡、美觀與易用的交互式命令提示工具
npm 安裝依啰,不必多言
npm install prompts
我們來實現(xiàn)一個簡易表單,獲取某射擊游戲店枣,玩家輸入的用戶名速警、密碼、年齡等基本信息:
const prompts = require('prompts');
~async function () {
const createChoice = (title, disable) => ({ title, value: title, disable: !!disable });
const res = await prompts([
{
type: 'text', // 文字類型
name: 'user',
message: 'input user'
},
{
type: 'password', // 密碼類型
name: 'password',
message: 'input: password'
},
{
type: 'number', // 數(shù)字類型
name: 'age',
message: 'input age'
},
{
type: 'select', // 單選
name: 'gender',
message: 'your gender',
choices: [createChoice('male'), createChoice('female'), createChoice('others')]
},
{
type: 'multiselect', // 多選
name: 'weapons',
message: 'select your weapon',
choices: [
createChoice('M16A4'),
createChoice('AK-74'),
createChoice('QBZ-95'),
createChoice('MP5'),
createChoice('P90'),
createChoice('Kar-98K'),
createChoice('Dragunov'),
createChoice('DesertEagle'),
createChoice('Glock-18'),
]
}
]);
console.log(JSON.stringify(res));
}();
運(yùn)行腳本鸯两,填單過程如下闷旧,與上文 vue 腳手架工具相差無幾:
√ input user ... Soap
√ input: password ... ***
√ input age ... 33
√ your gender ? male
? select your weapon ?
Instructions:
↑/↓: Highlight option
←/→/[space]: Toggle selection
a: Toggle all
enter/return: Complete answer
(*) M16A4
( ) AK-74
( ) QBZ-95
( ) MP5
( ) P90
( ) Kar-98K
( ) Dragunov
(*) DesertEagle
(*) Glock-18
最后輸出結(jié)果:
{"user":"Soap","password":"141","age":33,"gender":"male","weapons":["M16A4","DesertEagle","Glock-18"]}