NodeJs有許多命令行工具。它們全局安裝,並提供一個命令供咱們使用,完成相應的功能。 如今咱們就用node來開發一個實用的命令行小工具
1.首先咱們新建一目錄,而後執行npm init
生成package.json文件javascript
2.新建一bin目錄並在目錄下建立一個hi.jshtml
#! /usr/bin/env node console.log("hi")
執行node hi.js
咱們能夠看到終端輸出‘hi’。。固然這並非咱們要的命令行工具,咱們須要直接運行hi
就可出現結果java
3.如今咱們告訴npm可執行文件是哪一個,在package.json裏添加以下信息:node
"bin": { "hi": "bin/hi.js" }
npm link
如今咱們執行npm link
啓用命令行,如今再試試在終端直接輸入hi
命令,此次咱們能夠如願見到結果git
命令行參數可經過系統變量process.argv
獲取。 process.argv返回一個數組 第一個是node 第二個是腳本文件 第三個是輸入的參數,process.argv[2]
開始獲得纔是真正的參數部分github
#! /usr/bin/env node let argv = process.argv.slice(2) let yourName = argv[0] console.log(`hi, ${yourName}!`) // 執行 hi liu // hi, liu!
對於參數處理,咱們通常使用commander,commander是一個輕巧的nodejs模塊,提供了用戶命令行輸入和參數解析強大功能如:自記錄代碼、自動生成幫助、合併短參數(「ABC」==「-A-B-C」)、默認選項、強制選項、命令解析、提示符npm
$ npm install commander --save
#!/usr/bin/env node /** * Module dependencies. */ var program = require('commander') program .version('0.0.1') .option('-p, --peppers', 'Add peppers') .option('-P, --pineapple', 'Add pineapple') .option('-b, --bbq-sauce', 'Add bbq sauce') .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') .parse(process.argv) console.log('you ordered a pizza with:') if (program.peppers) console.log(' - peppers') if (program.pineapple) console.log(' - pineapple') if (program.bbqSauce) console.log(' - bbq') console.log(' - %s cheese', program.cheese)
Option()
: 初始化自定義參數對象,設置「關鍵字」和「描述」Command()
: 初始化命令行參數對象,直接得到命令行輸入Command#command()
: 定義一個命令名字Command#action()
: 註冊一個callback函數Command#option()
: 定義參數,須要設置「關鍵字」和「描述」,關鍵字包括「簡寫」和「全寫」兩部分,以」,」,」|」,」空格」作分隔。Command#parse()
: 解析命令行參數argvCommand#description()
: 設置description值Command#usage()
: 設置usage值除了commander外,yargs也是一個優秀的命令行參數處理模塊json
新建 文件夾translator/進入目錄下執行npm init
生成package.json文件api
npm install commander superagent cli-table2 --save
新建bin/translator.js文件,並加入package.json文件中數組
"bin": { "translator": "bin/translator.js" },
而後
npm link
這裏咱們會用到有道API
一切準備就緒咱們就能夠進行編碼了
因爲代碼量很小,這裏就直接貼代碼,在代碼中以註釋講解
#! /usr/bin/env node // 引入須要的模塊 const program = require('commander') const Table = require('cli-table2') // 表格輸出 const superagent = require('superagent') // http請求 // 初始化commander program .allowUnknownOption() .version('0.0.1') .usage('translator <cmd> [input]') // 有道api const API = 'http://fanyi.youdao.com/openapi.do?keyfrom=toaijf&key=868480929&type=data&doctype=json&version=1.1' // 添加自定義命令 program .command('query') .description('翻譯輸入') .action(function(word) { // 發起請求 superagent.get(API) .query({ q: word}) .end(function (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') } // 輸出表格 let table = new Table() table.push(result) console.log(table.toString()) }) }) // 沒有參數時顯示幫助信息 if (!process.argv[2]) { program.help(); console.log(); } program.parse(process.argv)
如今在終端中愉快的使用translator
了
$ translator Usage: translator <cmd> [input] Commands: query 翻譯輸入 Options: -h, --help output usage information -V, --version output the version number
拋磚引玉,更多請參考各個模塊的官方示例及API文檔
你們能夠關注個人公衆號,一塊兒玩耍。有技術乾貨也有扯淡亂談,關注回覆[888]領取福利
左手代碼右手磚,拋磚引玉