用node開發(fā)并發(fā)布一個cli工具的方法步驟
cli本質(zhì)是一種用戶操作界面,根據(jù)一些指令和參數(shù)來與程序完成交互并得到相應(yīng)的反饋,好的cli還提供幫助信息,我們經(jīng)常使用的vue-cli就是一個很好的例子。本文將使用nodejs從頭開發(fā)并發(fā)布一款cli工具,用來查詢天氣。
項(xiàng)目效果圖如下:
配置項(xiàng)目
初始化一個項(xiàng)目: npm init -y 編寫入口文件index.js:
module.exports = function(){
console.log('welcome to Anderlaw weather')
}
創(chuàng)建bin文件
bin目錄下創(chuàng)建index:
#!/usr/bin/env node
require('../')()
package.json配置bin信息
{
"name": "weather",
"version": "1.0.0",
"description": "",
"main": "index.js",
"bin": {
"weather": "bin/index"
}
}
然后在根目錄(package.json同級)運(yùn)行 npm link ,該操作會將該項(xiàng)目的模塊信息和bin指令信息以軟鏈接的形式添加到npm全局環(huán)境中:
C:\Users\mlamp\AppData\Roaming\npm\node_modules下多了一個模塊鏈接C:\Users\mlamp\AppData\Roaming\npm下多了個名為weather的cmd文件。
好處是可以更方便地進(jìn)行本地調(diào)試。 然后我們打開終端輸入: weather 就會看到 welcome to Anderlaw weather 的log信息
解析命令與參數(shù)
此處我們使用 minimist 庫來解析如:npm --save ,npm install 的參數(shù)。
安裝依賴庫 npm i -S minimist
使用 process.argv 獲取完整的輸入信息
使用 minimist 解析,例如:
weather today === args:{_:['today']}
weather -h === args:{ h:true }
weather --location 'china' === args:{location:'china'}
首先我們要實(shí)現(xiàn)查詢今天和明天的天氣,執(zhí)行 weather today[tomorrow]
const minimist = require('minimist');
module.exports = ()=>{
const args = minimist(process.argv.slice(2));//前兩個是編譯器相關(guān)路徑信息,可以忽略
let cmd = args._[0];
switch(cmd){
case 'today':
console.log('今天天氣不錯呢,暖心悅目!');
break;
case 'tomorrow':
console.log('明天下大雨,注意帶雨傘!');
break;
}
}
以上,如果我們輸入 weather 就會報錯,因?yàn)闆]有取到參數(shù).而且還沒添加版本信息,因此我們還需要改善代碼
const minimist = require('minimist')
const edition = require('./package.json').version
module.exports = ()=>{
const args = minimist(process.argv.slice(2));//前兩個是編譯器相關(guān)路徑信息,可以忽略
let cmd = args._[0] || 'help';
if(args.v || args.version){
cmd = 'version';//查詢版本優(yōu)先!
}
switch(cmd){
case 'today':
console.log('今天天氣不錯呢,暖心悅目!');
break;
case 'tomorrow':
console.log('明天下大雨,注意帶雨傘!');
break;
case 'version':
console.log(edition)
break;
case 'help':
console.log(`
weather [command] <options>
today .............. show weather for today
tomorrow ............show weather for tomorrow
version ............ show package version
help ............... show help menu for a command
`)
}
}
接入天氣API
截止目前工作順利進(jìn)行,我們還只是手工輸入的一些mock信息,并沒有真正的實(shí)現(xiàn)天氣的查詢。 要想實(shí)現(xiàn)天氣查詢,必須借助第三方的API工具,我們使用心知天氣提供的免費(fèi)數(shù)據(jù)服務(wù)接口。
需要先行注冊,獲取API key和id 發(fā)送請求我們使用axios庫(http客戶請求庫)
安裝依賴: npm i -S axios 封裝http模塊
///ajax.js
const axios = require('axios')
module.exports = async (location) => {
const results = await axios({
method: 'get',
url: 'https://api.seniverse.com/v3/weather/daily.json',
params:{
key:'wq4aze9osbaiuneq',
language:'zh-Hans',
unit:'c',
location
}
})
return results.data
}
該模塊接收一個 地理位置 信息返回今天、明天、后臺的天氣信息。
例如查詢上海今天的天氣: weather today --location shanghai
修改入口文件,添加 async標(biāo)志
const minimist = require('minimist')
const ajax = require('./ajax.js')
const edition = require('./package.json').version
module.exports = async ()=>{
const args = minimist(process.argv.slice(2));//前兩個是編譯器相關(guān)路徑信息,可以忽略
let cmd = args._[0] || 'help';
if(args.v || args.version){
cmd = 'version';//查詢版本優(yōu)先!
}
let location = args.location || '北京';
let data = await ajax(location);
data = data.results[0];
let posotion= data.location;
let daily = data.daily;
switch(cmd){
case 'today':
//console.log('今天天氣不錯呢,暖心悅目!');
console.log(`${posotion.timezone_offset}時區(qū),${posotion.name}天氣,${posotion.country}`)
console.log(`今天${daily[0].date}:白天${daily[0].text_day}夜晚${daily[0].text_night}`)
break;
case 'tomorrow':
//console.log('明天下大雨,注意帶雨傘!');
console.log(`${posotion.timezone_offset}時區(qū),${posotion.name}天氣,${posotion.country}`)
console.log(`今天${daily[1].date}:白天${daily[1].text_day}夜晚${daily[1].text_night}`)
break;
case 'version':
console.log(edition)
break;
case 'help':
console.log(`
weather [command] <options>
today .............. show weather for today
tomorrow ............show weather for tomorrow
version ............ show package version
help ............... show help menu for a command
`)
}
}
我們輸入 weather today --location shanghai ,發(fā)現(xiàn)有結(jié)果了:
修修補(bǔ)補(bǔ),添加loading提示和默認(rèn)指令
截止當(dāng)前,基本完成了功能開發(fā),后續(xù)有一些小問題需要彌補(bǔ)一下,首先是一個進(jìn)度提示,使用起來就更加可感知,我們使用 ora 庫.
其次我們需要當(dāng)用戶輸入無匹配指令時給予一個引導(dǎo),提供一個默認(rèn)的log提示。
安裝依賴 npm i -S ora
編寫loading模塊:
const ora = require('ora')
module.exports = ora()
// method start and stop will be use
修改入口文件
const minimist = require('minimist')
const ajax = require('./ajax.js')
const loading = require('./loading')
const edition = require('./package.json').version
module.exports = async ()=>{
const args = minimist(process.argv.slice(2));//前兩個是編譯器相關(guān)路徑信息,可以忽略
let cmd = args._[0] || 'help';
if(args.v || args.version){
cmd = 'version';//查詢版本優(yōu)先!
}
let location = args.location || '北京';
loading.start();
let data = await ajax(location);
data = data.results[0];
let posotion= data.location;
let daily = data.daily;
switch(cmd){
case 'today':
//console.log('今天天氣不錯呢,暖心悅目!');
console.log(`${posotion.timezone_offset}時區(qū),${posotion.name}天氣,${posotion.country}`)
console.log(`今天${daily[0].date}:白天${daily[0].text_day}夜晚${daily[0].text_night}`)
loading.stop();
break;
case 'tomorrow':
//console.log('明天下大雨,注意帶雨傘!');
console.log(`${posotion.timezone_offset}時區(qū),${posotion.name}天氣,${posotion.country}`)
console.log(`今天${daily[1].date}:白天${daily[1].text_day}夜晚${daily[1].text_night}`)
loading.stop();
break;
case 'version':
console.log(edition)
loading.stop();
break;
case 'help':
console.log(`
weather [command] <options>
today .............. show weather for today
tomorrow ............show weather for tomorrow
version ............ show package version
help ............... show help menu for a command
`)
loading.stop();
default:
console.log(`你輸入的命令無效:${cmd}`)
loading.stop();
}
}
發(fā)布
發(fā)布至npm倉庫之后 可以直接以npm i -g weather全局方式安裝我們發(fā)布的cli,并在任何地方輸入weather命令查詢天氣了喲!
如果不清楚如何發(fā)布可查看我的另一篇文章發(fā)布一款npm包幫助理解npm
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
30分鐘用Node.js構(gòu)建一個API服務(wù)器的步驟詳解
這篇文章主要介紹了30分鐘用Node.js構(gòu)建一個API服務(wù)器的步驟詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05
Node.js 使用axios讀寫influxDB的方法示例
這篇文章主要介紹了Node.js 使用axios讀寫influxDB的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
Mongoose中document與object的區(qū)別示例詳解
這篇文章主要給大家介紹了關(guān)于Mongoose中document與object區(qū)別的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
node事件循環(huán)和process模塊實(shí)例分析
這篇文章主要介紹了node事件循環(huán)和process模塊,結(jié)合實(shí)例形式分析了node事件循環(huán)和process模塊具體功能、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2020-02-02
基于NodeJS的前后端分離的思考與實(shí)踐(六)Nginx + Node.js + Java 的軟件棧部署實(shí)踐
關(guān)于前后端分享的思考,我們已經(jīng)有五篇文章闡述思路與設(shè)計。本文介紹淘寶網(wǎng)收藏夾將 Node.js 引入傳統(tǒng)技術(shù)棧的具體實(shí)踐。2014-09-09
Node.js中.npmrc文件的配置實(shí)現(xiàn)
.npmrc?文件是 npm 配置的核心文件,用于管理 npm 的行為,本文就來介紹一下Node .npmrc文件配置,具有一定的參考價值,感興趣的可以了解一下2024-12-12
node.js中的http.response.getHeader方法使用說明
這篇文章主要介紹了node.js中的http.response.getHeader方法使用說明,本文介紹了http.response.getHeader的方法說明、語法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12

