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

Nodejs 利用Commander写自己的 命令行工具_第1张图片

关注公众号"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  [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

你可能感兴趣的:(nodejs)