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

3次阅读

共计 1690 个字符,预计需要花费 5 分钟才能阅读完成。

方法一:通过原生的 NodeJs API,方法如下:

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

通过以下命令执行:

node test.js param1 --param2 -param3

结果输出如下:

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

可见,argv 中第一个参数为 node 应用程序的路径,第二个参数为被执行的 js 程序文件,其余为执行参数。
方法二:通过 yargs 获取命令行参数,方法如下:
首先,需要在项目中引入该模块:
npm install –save args
然后,创建 JS 可执行程序,如下:

#!/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]

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

示例:

  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/…

正文完
 0