In essence, CLI is a user interface, according to some instructions and parameters to complete the interaction with the program and get the corresponding feedback, a good CLI also provides help information, we often use vue-CLI is a good example. In this article, you will use NodeJS to develop and release a CLI tool to query the weather from scratch.
The renderings of the project are as follows:
Configuration items
To initialize a project: NPM init -y write entry file index.js:
module.exports = function(){
console.log('welcome to Anderlaw weather')}Copy the code
Creating a bin file
Create index in bin directory:
#! /usr/bin/env node
require('.. / ') ()Copy the code
Package. json Configures bin information
{
"name": "weather"."version": "1.0.0"."description": ""."main": "index.js"."bin": {
"weather": "bin/index"}}Copy the code
Then run NPM Link in the root directory (at the same level as package.json). This will add the module information of the project and the bin directive information to the NPM global as a soft link:
C:\Users\mlamp\AppData\Roaming\npm\node_modules
There is an extra module linkC:\Users\mlamp\AppData\Roaming\npm
It’s got a nameweather
CMD file.
The benefit is that it is easier to debug locally. Then we open the terminal and type: weather to see the welcome to Anderlaw weather log
Parse commands and parameters
Here we use the Minimist library to parse parameters such as NPM –save, NPM install.
Install the dependency library NPM i-S Minimist
Use process.argv to get complete input information
Use the minimist analysis, for example:
weather today === args:{_:['today']}
weather -h === args:{ h:true }
weather --location 'china' === args:{location:'china'}
Copy the code
First we need to implement the query for today’s weather and tomorrow’s weather by executing weather today[tomorrow]
const minimist = require('minimist');
module.exports = (a)= >{
const args = minimist(process.argv.slice(2));// The first two are compiler path information and can be ignored
let cmd = args._[0];
switch(cmd){
case 'today':
console.log('It's a nice day today, warm heart and pleasing to the eye! ');
break;
case 'tomorrow':
console.log('It's going to rain hard tomorrow, so take your umbrella with you! ');
break; }}Copy the code
Above, if we type in weather we get an error because we don’t get the parameter. And we haven’t added the version information yet, so we still need to improve the code
const minimist = require('minimist')
const edition = require('./package.json').version
module.exports = (a)= >{
const args = minimist(process.argv.slice(2));// The first two are compiler path information and can be ignored
let cmd = args._[0] | |'help';
if(args.v || args.version){
cmd = 'version';// Query version first!
}
switch(cmd){
case 'today':
console.log('It's a nice day today, warm heart and pleasing to the eye! ');
break;
case 'tomorrow':
console.log('It's going to rain hard tomorrow, so take your umbrella with you! ');
break;
case 'version':
console.log(edition)
break;
case 'help':
console.log(` weather [command]
today .............. show weather for today tomorrow ............ show weather for tomorrow version ............ show package version help ............... show help menu for a command `
)}}Copy the code
Access the Weather API
So far, the work is going smoothly, we just mock some information manually input, and do not really implement the weather query. To do this, you have to use a third party API tool. We use the free data service interface provided by Heartknow Weather.
We need to register first, get the API key and ID to send the request and we use the Axios library
Install dependencies: NPM i-s AXIos encapsulates HTTP modules
///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
}
Copy the code
The module receives a location information to return today, tomorrow, the background of the weather information.
For example, to query the weather in Shanghai today: weather today –location Shanghai
Modify the entry file to add the async flag
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));// The first two are compiler path information and can be ignored
let cmd = args._[0] | |'help';
if(args.v || args.version){
cmd = 'version';// Query version first!
}
let location = args.location || 'Beijing';
let data = await ajax(location);
data = data.results[0];
let posotion= data.location;
let daily = data.daily;
switch(cmd){
case 'today':
//console.log(' What a nice day! ');
console.log(`${posotion.timezone_offset}Time zones,${posotion.name}The weather,${posotion.country}`)
console.log(` today${daily[0].date}During the day:${daily[0].text_day}night${daily[0].text_night}`)
break;
case 'tomorrow':
//console.log(' It's going to rain hard tomorrow. ');
console.log(`${posotion.timezone_offset}Time zones,${posotion.name}The weather,${posotion.country}`)
console.log(` today${daily[1].date}During the day:${daily[1].text_day}night${daily[1].text_night}`)
break;
case 'version':
console.log(edition)
break;
case 'help':
console.log(` weather [command]
today .............. show weather for today tomorrow ............ show weather for tomorrow version ............ show package version help ............... show help menu for a command `
)}}Copy the code
Weather today –location Shanghai
Tinkering, adding loading prompt and default instruction
Up to now, the function development has been basically completed, but there are some minor problems to be remedied in the future. The first is a progress hint, which makes it more perceptifiable to use. We use the ORA library.
Second, we need to give a boot when the user enters a no-match instruction, providing a default log hint.
The installation is dependent on NPM i-S ora
Write a loading module:
const ora = require('ora')
module.exports = ora()
// method start and stop will be use
Copy the code
Modify entry file
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));// The first two are compiler path information and can be ignored
let cmd = args._[0] | |'help';
if(args.v || args.version){
cmd = 'version';// Query version first!
}
let location = args.location || 'Beijing';
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(' What a nice day! ');
console.log(`${posotion.timezone_offset}Time zones,${posotion.name}The weather,${posotion.country}`)
console.log(` today${daily[0].date}During the day:${daily[0].text_day}night${daily[0].text_night}`)
loading.stop();
break;
case 'tomorrow':
//console.log(' It's going to rain hard tomorrow. ');
console.log(`${posotion.timezone_offset}Time zones,${posotion.name}The weather,${posotion.country}`)
console.log(` today${daily[1].date}During the day:${daily[1].text_day}night${daily[1].text_night}`)
loading.stop();
break;
case 'version':
console.log(edition)
loading.stop();
break;
case 'help':
console.log(` weather [command]
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('The command you entered is invalid:${cmd}`) loading.stop(); }}Copy the code
release
NPM i-g weather = NPM i-g weather = NPM i-g weather = NPM i-g weather = NPM i-g weather = NPM i-g weather
If you’re not sure how to publish, see another of my articles: Publish an NPM package to help understand NPM
In this paper, finished!