前端技術之:如何建立一個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

相關文章
相關標籤/搜索