Thought Works 西邮联合创新实验室

使用inquirer,chalk来创建一个交互式的nodejs-

2019-06-02  本文已影响0人  Gaarahan

官方有详细的文档,只记录自己用到的,方便后面查阅


inquirer.js ---- 提供命令行与用户的交互接口

var inquirer = require('inquirer');
inquirer
  .prompt([
    /* Pass your questions in here */
  ])
  .then(answers => {
    // Use user feedback for... whatever!!
  });
[{
  name : "han", //展示出来的选项
  value :  "gaara han", //该选项实际对应的值
  short : "h", //选择后展示的简称
},...]

还可以在其中使用inquirer提供的分隔符类

简单尝试

const inquirer = require('inquirer');
inquirer.prompt([
  {
    name : 'my-name',
    type : 'list',
    message : 'which of this is my name?',
    default : 'i don\'t know',
    choices : [
      {
        name : 'gaara han',
        value : 'gaara han',
        short : 'gaara',
      },
      {
        name : 'han',
        value : 'han',
        short  : 'han',
      },
      {
        name : "i don't know",
        value : 'undefined',
        short : 'no-name'
      },
    ],
  }
]).then(ans=>{
  console.log(ans);
})

chalk --- 给输出带上颜色

const chalk = require('chalk');
const log = console.log;
// 为普通字符串结合样式
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// 可以同时添加多个样式
log(chalk.blue.bgRed.bold('Hello world!'));
// 可以传递多个值
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// 可以相互嵌套
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
log(chalk.green(
  'I am a green line ' +
  chalk.blue.underline.bold('with a blue substring') +
  ' that becomes green again!'
));
// 支持模版字符串
log(`
  CPU: ${chalk.red('90%')}
  RAM: ${chalk.green('40%')}
  DISK: ${chalk.yellow('70%')}
  `);
let cpu = { totalPercent : 80, }
let ram = { used : 4, tota : 8, }
let disk = { used : 20, total : 50, }
log(chalk`
  CPU: {red ${cpu.totalPercent}%}
  RAM: {green ${ram.used / ram.total * 100}%}
  DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
  `);
// 使用关键字,rgb,十六进制
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
上一篇 下一篇

猜你喜欢

热点阅读