前端技术之:如何建立一个NodeJs命令行交互项目

方法一:经过原生的NodeJs API,方法以下:node

#!/usr/bin/env node
# test.js
var argv = process.argv;
console.log(argv)

经过如下命令执行:git

node test.js param1 --param2 -param3

结果输出以下:github

[ '/usr/local/Cellar/node/10.10.0/bin/node',
  'test.js',
  'param1',
  '--param2',
  '-param3' ]

可见,argv中第一个参数为node应用程序的路径,第二个参数为被执行的js程序文件,其他为执行参数。npm

方法二:经过yargs获取命令行参数,方法以下: 首先,须要在项目中引入该模块: npm install --save args 而后,建立JS可执行程序,以下:ui

#!/usr/bin/env node

var args = require('yargs');

const argv = args.option('n', {
alias : 'name',
demand: true,
default: 'tom',
describe: 'your name',
type: 'string'
})
.usage('Usage: hello [options]')
.example('hello -n bob', 'say hello to Bob')
.help('h')
.alias('h', 'help')
.argv;

console.log('the args:', argv)

执行以下命令:命令行

node test.js -h

显示结果以下: Usage: hello [options]rest

选项: --version 显示版本号 [布尔] -n, --name your name [字符串] [必需] [默认值: "tom"] -h, --help 显示帮助信息 [布尔]code

示例:orm

hello -n bob  say hello to Bob

执行以下命令:字符串

node test.js -n Bobbbb 'we are friends'

结果显示以下:

the args: { _: [ 'we are friends' ],
  n: 'Bobbbb',
  name: 'Bobbbb',
  '$0': 'test.js' }

可见,经过yargs开源NPM包,能够很容易定义命令行格式,并方便地获取各类形式的命令行参数。 经过yargs虽然能够很方便地定义并获取命令行参数,但不能很好地解决与命令行的交互,并且参数的数据类型也比较受局限。因此,咱们看一下另一个开源项目。

方法三:经过inquirer开源项目实现交互命令 建立test.js文件:

#!/usr/bin/env node

var inquirer = require("inquirer");
inquirer
  .prompt([
    {
      type: "input",
      name: "name",
      message: "controller name please",
      validate: function(value) {
        if (/.+/.test(value)) {
          return true;
        }
        return "name is required";
      }
    },
    {
      type: "list",
      name: "type",
      message: "which type of conroller do you want to create?",
      choices: [
        { name: "Normal Controller", value: "", checked: true },
        { name: "Restful Controller", value: "rest" },
        { name: "View Controller", value: "view" }
      ]
    }
  ])
  .then(answers => {
    console.log(answers);
  });

执行程序:

node test.js

输出结果:

? controller name please test
? which type of conroller do you want to create? Normal Controller
{ name: 'test', type: '' }

参考资料: https://github.com/yargs/yargs https://github.com/SBoudrias/Inquirer.js

相关文章
相关标签/搜索