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

发布时间:2020-06-15 21:48:49 作者:popgis
来源:网络 阅读:264

方法一:通过原生的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/Inquirer.js

推荐阅读:
  1. 前端技术之:命令模块及其执行方法
  2. 前端技术之:JavaScript Test 断言库

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

yargs inquirer 命令行

上一篇:数据库指定库表中的字段进行备份,并以表格的形式定时发送邮件到指定邮箱 ​

下一篇:消息中间件之ActiveMQ

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》