前端技術之:如何創建一個NodeJs命令行交互項目

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章