前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >node命令交互inquirer

node命令交互inquirer

作者头像
wade
发布2021-03-15 15:05:28
8230
发布2021-03-15 15:05:28
举报

用过vue或者react的用脚手架新建项目的应该都进行过命令交互,vue创建的时候会让你选择vue2还是vue3,也有多选要什么配置,也有输入y或者n选择是否用history路由等,这其实用inquire这个包都能实现。

环境跟之前commander使用是一样的,初始化之后配置bin和npm link一下,这边就不再说了。

安装inquirer:

npm install inquirer

引入:

var inquirer = require('inquirer');

inquirer主要知道这几个类型类型,其他的有兴趣再去了解:

input,confirm,list,checkbox,password

方法用prompt就行,另外两个registerPrompt和createPromptModule也可以自己去了解。

我们按照顺序都展示出来,不管输入还是选择了什么,都继续下一种类型展示,代码:

typeInput();

function typeInput() {
  inquirer.prompt([ {
    name: 'input',
    type: 'input',
    message: 'input: year, month and day',
    default: 'year'
  }]).then((res) => {
    console.log('Year: ' + res.input);
    typeConfirm();
  })
}

function typeConfirm(){
  inquirer.prompt([ {
    name: 'confirm',
    type: 'confirm',
    message: 'confirm',
    default: true
  }]).then((res) => {
    console.log('confirm: ' + res.confirm);
    typeList();
  })
}

function typeList(){
  inquirer.prompt([ {
    name: 'list',
    type: 'list',
    message: 'list',
    choices: ['red', 'blue', 'yellow'],
    default: 1
  }]).then((res) => {
    console.log('list: ' + res.list);
    typeCheckbox();
  })
}

function typeCheckbox(){
  inquirer.prompt([ {
    name: 'checkbox',
    type: 'checkbox',
    message: 'checkbox',
    choices: ['red', 'blue', 'yellow'],
    default: ['blue']
  }]).then((res) => {
    console.log('checkbox: ' + res.checkbox);
    typePassword();
  })
}

function typePassword(){
  inquirer.prompt([ {
    name: 'password',
    type: 'password',
    message: 'password',
    mask: false //是否出现*号
  }]).then((res) => {
    console.log('password: ' + res.password);
  })
}

prompt方法返回的是Promise,用的时候也可以配合async和await,返回的字段就是name字段:

typeCheckbox();
async function typeCheckbox() {
  let {checkbox} = await inquirer.prompt([
    {
      name: 'checkbox',
      type: 'checkbox',
      message:'checkbox',
      choices: ['red', 'blue', 'yellow'],
      default: ['blue']
    }
  ]);
  console.log('checkbox ' + checkbox);
}

效果:

commander和inquirer可以说是命令行交互最基本的两个包,这两个包的基本用法已经足够我们去开发一个cli的命令行交互操作。

(完)

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-03-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 coding个人笔记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档