NodeJs交互式命令行工具Inquirer.js

安裝

  npm install inquirer
  const inquirer = require('inquirer')
  inquirer.prompt([
      /* Pass your questions in here */
  ]).then(answers => {
    // Use user feedback for... whatever!!
  })

參數(shù)

   type: String, // 表示提問的類型,下文會單獨解釋 name: String, // 在最后獲取到的answers回答對象中,作為當前這個問題的鍵
  message: String|Function, // 打印出來的問題標題,如果為函數(shù)的話 
  default: String|Number|Array|Function, // 用戶不輸入回答時,問題的默認值?;蛘呤褂煤瘮?shù)來return一個默認值。假如為函數(shù)時,函數(shù)第一個參數(shù)為當前問題的輸入答案。 
  choices: Array|Function, // 給出一個選擇的列表,假如是一個函數(shù)的話,第一個參數(shù)為當前問題的輸入答案。為數(shù)組時,數(shù)組的每個元素可以為基本類型中的值。 
  validate: Function, // 接受用戶輸入,并且當值合法時,函數(shù)返回true。當函數(shù)返回false時,一個默認的錯誤信息會被提供給用戶。 
  filter: Function, // 接受用戶輸入并且將值轉化后返回填充入最后的answers對象內(nèi)。 
  when: Function|Boolean, // 接受當前用戶輸入的answers對象,并且通過返回true或者false來決定是否當前的問題應該去問。也可以是簡單類型的值。 
  pageSize: Number, // 改變渲染list,rawlist,expand或者checkbox時的行數(shù)的長度。}
  • when 根據(jù)answer 返回結果判斷是否執(zhí)行該問題
  • filter 過濾一些錯誤輸入

一小段代碼的優(yōu)化過程:

  • 第一版
  const inquirer = require('inquirer')
  const shell = require('shelljs')
  const qustion = [
     {
    name: 'conf',
    type: 'confirm',
    message: '建議上線前選擇全部測試用例(默認為測試全部)',
    },
  ]
 const qustion2 = [
    {
      {
    name: 'project',
    message: 'Please input the project name which you want to check:',
    filter: src => src.replace(/.spec.ts$/gi, ''),
    validate: str => Boolean(str.split('/').length === 2 || str.split('/').length ===   3),
    when: res => !Boolean(res.conf)
  }
]
const prompt1 = () => new Promise(resolve => {
  inquirer.prompt(question).then(({ conf
 }) => {
    let params = '**/**/*'
    resolve({
      params,
      conf
    })
  })
})
const prompt2 = () => new Promise(resolve => {
  inquirer.prompt(question2).then(({ project }) => {
    let arg = project
   if (reg.test(project)) {
      arg = project.replace(/.spec.ts$/gi, '')
    }
    resolve({
      arg,
    })
  })
})
prompt1().then(({ params, conf}) => {
 if (conf) {
  shell.exec(`
  mocha -r ts-node/register test/${params}.spec.ts --colors
`, { async: true })
} else {
  prompt2().then(({ arg }) => {
     shell.exec(`
  mocha -r ts-node/register test/${arg}.spec.ts --colors
`, { async: true })
  })
}
})

可以看到第一版的代碼冗余較多,感覺很low

  • 第二版
const inquirer = require('inquirer')
const shell = require('shelljs')
// Node colorful always

const questions = [
  {
    name: 'conf',
    type: 'confirm',
    message: '建議上線前選擇全部測試用例(默認為測試全部)',
  },
  {
    name: 'project',
    message: 'Please input the project name which you want to check:',
    filter: src => src.replace(/.spec.ts$/gi, ''),
    validate: str => Boolean(str.split('/').length === 2 || str.split('/').length === 3),
    when: res => !Boolean(res.conf)
  },
]

const prompts = () => new Promise(resolve => {
  inquirer.prompt(questions).then(({ conf, project }) => {
    let params = '**/**/*'
    const reg = /spec.ts$/
    if (!conf) {
      params = project
       if (reg.test(project)) {
         params = project.replace(/.spec.ts$/gi, '')
       }
    }
    resolve({
      params,
    })
  })
})


prompts().then(({ params}) => {
  shell.exec(`
  mocha -r ts-node/register test/${params}.spec.ts --colors
`, { async: true })
})

可以看到第二版相對于第一版縮減了一半的代碼量, 用when 去判斷是否讀取問題

  • 最終版 (將所有判斷在inquirer question 參數(shù)中完成)
  const inquirer = require('inquirer')
const shell = require('shelljs')
// Node colorful always

const questions = [
  {
    name: 'conf',
    type: 'confirm',
    message: '建議上線前選擇全部測試用例(默認為測試全部)',
  },
  {
    name: 'project',
    message: 'Please input the project name which you want to check:',
    filter: src => src.replace(/.spec.ts$/gi, ''),
    validate: str => Boolean(str.split('/').length === 2 || str.split('/').length === 3),
    when: res => !Boolean(res.conf)
  },
]

const prompts = () => new Promise(resolve => {
  inquirer.prompt(questions).then(({ conf,  project }) => {
    let params = '**/**/*'
    if (!conf) {
      params = project
    }
    resolve({
      params,
    })
  })
})


prompts().then(({ params}) => {
  shell.exec(`
  mocha -r ts-node/register test/${params}.spec.ts --colors
`, { async: true })
})

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • Inquirer.js試圖為NodeJs做一個可嵌入式的美觀的命令行界面。如下圖: 提供錯誤回調(diào) 詢問操作者問題 ...
    SherHoooo閱讀 19,321評論 2 8
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標準。 注意:講述HT...
    kismetajun閱讀 27,749評論 1 45
  • 輸入 y ,創(chuàng)建 git_hug 目錄No githug directory found, do you wish...
    風花花閱讀 1,982評論 0 4
  • 現(xiàn)代人總是處在兩種不幸福的狀態(tài),不是因為生活平淡而覺得無聊,就是因為工作壓力太大而焦慮。而心流理論恰恰能對抗這些不...
    cfanr閱讀 3,464評論 1 0
  • 今早剛到公司不久,就被老寧批了一頓,原因是我不會工作。 是的,一個上班五年的人被批不會工作,我還是很受傷的,但是老...
    蘇揚儺葉閱讀 212評論 0 0