Nodejs 利用Commander寫自己的 命令行工具

image.png

關注公衆號"seeling_GIS",回覆『前端視頻』,領取前端學習視頻資料
前言

在使用Nodejs過程中,有很多包都支持全局安裝,然後提供一個命令,然後在命令行我們就可以完成一些任務,像 express, grunt, bower, yeoman, reap, karma, requirejs 等。有時候,我們也需要自己開發這樣的命令行工具。

commander.js,可以幫助我們簡化命令行的開發。

目錄

  1. commander介紹

  2. commander安裝

  3. commander的API

  4. 開發自定義的命令

  5. 發佈爲運行命令

1. commander介紹

commander是一個輕巧的nodejs模塊,提供了用戶命令行輸入和參數解析強大功能。commander源自一個同名的Ruby項目。

commander的特性:

  • 自記錄代碼

  • 自動生成幫助

  • 合併短參數(“ABC”==“-A-B-C”)

  • 默認選項

  • 強制選項

  • 命令解析

  • 提示符

2. commander安裝

我的系統環境

  • win10 64bit

  • Nodejs:v12.16.1

  • Npm:6.13.6

  • 新建並初始化項目

    npm init
    

安裝commander等依賴

npm install commander cli-table2 superagent

編寫一個簡單的例子:增加文件app.js

const { program } = require('commander');

命令行輸入測試:

無參數

PS F:\Codes\github\nodejs\commanderTest> node .\app.js       

一個參數

PS F:\Codes\github\nodejs\commanderTest> node .\app.js -d

多個參數

PS F:\Codes\github\nodejs\commanderTest> node .\app.js -ds -p bbq -l aa,bb,cc

help

PS F:\Codes\github\nodejs\commanderTest> node .\app.js --help

Version

PS F:\Codes\github\nodejs\commanderTest> node .\app.js -V

3. commander的API

  • Option(): 初始化自定義參數對象,設置“關鍵字”和“描述”

  • Command(): 初始化命令行參數對象,直接獲得命令行輸入

  • Command#command(): 定義一個命令名字

  • Command#action(): 註冊一個callback函數

  • Command#option(): 定義參數,需要設置“關鍵字”和“描述”,關鍵字包括“簡寫”和“全寫”兩部分,以”,”,”|”,”空格”做分隔。

  • Command#parse(): 解析命令行參數argv

  • Command#description(): 設置description值

  • Command#usage(): 設置usage值

請參考API的官方例子:https://www.npmjs.com/package/commander

4. 開發一個自己的命令行工具,通過命令行來查詢有道字典

#! /usr/bin/env node
const {
    program
} = require('commander');
const Table = require('cli-table2') // 表格輸出
const superagent = require('superagent') // http請求 

function action(res) {
    console.log(res)
}
 
program
    .allowUnknownOption()
    .version('0.0.1')
    .usage('translator <cmd> [input]')

const url = `http://fanyi.youdao.com/openapi.do?keyfrom=toaijf&key=868480929&type=data&doctype=json&version=1.1`;

program
    .command('query')
    .description('翻譯輸入')
    .action((obj) => {
        let word = obj.args.join(' ');
        superagent.get(url)
            .query({
                q: word
            })
            .end(  (err, res)=> {
               
                if (err){
                    console.log('excuse me, try again')
                    return false
                } 
                let data = JSON.parse(res.text);
                let result ={}; 
                // 返回的數據處理
                if (data.basic) {
                    result[word] = data['basic']['explains'];
                } else if (data.translation) {
                    result[word] = data['translation'];
                } else {
                    console.error('error');
                }
                console.log()
                // 輸出表格
                let table = new Table();
                table.push(result);
                console.log(table.toString());
            })
    }); 
if (!process.argv[2]) {
    program.help();
    console.log();
}
program.parse(process.argv);

命令行輸入測試:

PS F:\Codes\github\nodejs\commanderTest> node .\youdao.js query someone

┌─────────┬────────────────────────────┐
│ someone │ pron. 有人,某人;重要人物   │
└─────────┴────────────────────────────┘
  1. 命令行工具部署

1. 在package.json 裏面添加
"bin": { "youdao": "bin/youdao.js" },

2.  執行 npm link 設置全局調用

3.  執行結果:

 node youdao query my

┌────┬────────────┬───────────────────────────────┬─────────────────────────────────┐
│ my │ pron. 我的 │ int. 哎呀(表示驚奇等);喔唷 │ n. (My)人名;(越)美;(老、柬)米 │
└────┴────────────┴───────────────────────────────┴─────────────────────────────────┘

Cesium 基礎系列


【Cesium 基礎】vue3+cesium 環境搭建(一)

【Cesium 基礎】ImageryProvider 服務 (二)

【Cesium 基礎】Entity API(三)

『Cesium 基礎』Entity 樣式設置(四)

『Cesium 基礎』Cesium ion 在線資源調用(五)

『Cesium 基礎』Cesium Knockout 使用(六)

【Vue@Leaflet】系列


【Vue@Leaflet】初始化

【Vue@Leaflet】底圖 Baselayer

【vue@Leaflet】創建Leaflet組件

【vue@Leaflet】創建TileLayer組件


更多內容,歡迎關注公衆號
seeling_GIS

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