溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

前端技術(shù)之:如何創(chuàng)建一個(gè)NodeJs命令行交互項(xiàng)目

發(fā)布時(shí)間:2020-06-15 21:48:49 來(lái)源:網(wǎng)絡(luò) 閱讀:270 作者:popgis 欄目:web開(kāi)發(fā)

方法一:通過(guò)原生的NodeJs API,方法如下:

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

通過(guò)以下命令執(zhí)行:

node test.js param1 --param2 -param3

結(jié)果輸出如下:

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

可見(jiàn),argv中第一個(gè)參數(shù)為node應(yīng)用程序的路徑,第二個(gè)參數(shù)為被執(zhí)行的js程序文件,其余為執(zhí)行參數(shù)。

方法二:通過(guò)yargs獲取命令行參數(shù),方法如下:
首先,需要在項(xiàng)目中引入該模塊:
npm install --save args
然后,創(chuàng)建JS可執(zhí)行程序,如下:

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

執(zhí)行如下命令:

node test.js -h

顯示結(jié)果如下:
Usage: hello [options]

選項(xiàng):
--version 顯示版本號(hào) [布爾]
-n, --name your name [字符串] [必需] [默認(rèn)值: "tom"]
-h, --help 顯示幫助信息 [布爾]

示例:

  hello -n bob  say hello to Bob

執(zhí)行如下命令:

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

結(jié)果顯示如下:

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

可見(jiàn),通過(guò)yargs開(kāi)源NPM包,可以很容易定義命令行格式,并方便地獲取各種形式的命令行參數(shù)。
通過(guò)yargs雖然可以很方便地定義并獲取命令行參數(shù),但不能很好地解決與命令行的交互,而且參數(shù)的數(shù)據(jù)類(lèi)型也比較受局限。所以,我們看一下另外一個(gè)開(kāi)源項(xiàng)目。

方法三:通過(guò)inquirer開(kāi)源項(xiàng)目實(shí)現(xiàn)交互命令
創(chuàng)建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);
  });

執(zhí)行程序:

node test.js

輸出結(jié)果:

? 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

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI