使用 npm init
快速生成一个 package.json
来建立一个新的 npm
项目:javascript
{ "name": "happyday", "version": "1.0.5", "description": "Happy every day", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "Nodejs", "JavaScript", "bash", "shell" ], "repository": { "type": "git", "url": "git+https://github.com/HuangXiZhou/happyday.git" }, "author": "xizhouh@gmail.com", "license": "MIT" }
新建一个 index.js
包含咱们的脚本java
#!/usr/bin/env node // 说明这是一个可执行的应用 console.log('Happy everyday!')
在 package.json
中新建 bin
字段,用于存放一个可执行文件node
"bin": { "happyday": "./index.js" }
接着执行 npm i -g && npm link
把 happyday
这个字段复制到 npm
的全局模块安装文件夹 node_modules
内,并建立符号连接(symbolic link,软连接),也就是将 index.js
的路径加入环境变量 PATH
中去ios
运行 happyday
git
能够看到咱们已经成功打印出 Happy everyday!
,如今咱们能够开始开发 npm
包了github
安装 tj 大神的commander
: npm i commander -S
shell
The complete solution for node.js command-line interfaces, inspired by Ruby's commander.npm
安装 chalk
使得你的命令行更漂亮: npm i chalk -S
json
如今让咱们写一下 demo 测试一下:axios
#! /usr/bin/env node const program = require('commander') const chalk = require('chalk') program .command('weather') // 命令行指令 .alias('w') // 定义别名 .description(chalk.green('Get weather forecast ;)')) // 这行文字变绿~ // 注册一个 `callback` 函数 .action(option => { console.log('biubiubiu~') }) // 生成帮助信息 .on('--help', () => { console.log(' Examples:') console.log('') console.log('$ happyday weather') console.log('$ happyday w') }) program.parse(process.argv) // 解析命令行
执行一下 happyday -h
Usage: happyday [options] [command] Options: -h, --help output usage information Commands: weather|w Get weather forecast ;)
这样第一步就完成了,能够正式开发咱们的 天气预报 小玩具了
先在百度开发者中心注册一个 KEY
由于懒... 因此我直接引入 axios
实行 GET
请求:
const URL_IP = 'http://api.map.baidu.com/location/ip' const KEY = { ak: '...' } ... .action(option => { axios.get(URL_IP, { params: KEY }) .then(res => { console.log(res) }) .catch(error => { console.log(chalk.red('emmmmm... I don\'t know what happened.')) }) }) ...
先获取用户所在城市,再根据所在城市获取用户所在地的天气预报
const URL_FORECAST = 'http://api.map.baidu.com/telematics/v3/weather' const KEY = { ak: '...' } let getweatherModel = { location: '', output: 'json', ak: KEY.ak, } ... getweatherModel.location = res.data.content.address_detail.city axios.get(URL_FORECAST, { params: getweatherModel }) .then(res => { if(res.status !== 200) { console.log(chalk.red('Whoops!!! There is something wrong with your network.')) } else { let resource = res.data if(resource.status !== 'success') { console.log(chalk.red('emmmmm... I don\'t know what happened.')) } else { console.log(resource) } } }) .catch(error => { console.log(chalk.red('emmmmm... I don\'t know what happened.')) }) ...
获取到数据以后,让咱们处理一下数据
`城市: ${chalk.green(resource.results[0].currentCity)} ❤️`
打印天气预报
resource.results[0].weather_data.forEach(item => { console.log( `${item.date.slice(0, 2)}: ${chalk.green(item.weather)} | ${chalk.green(item.temperature)}` ) }, this)
这样,咱们的小玩具初步成型
然而... 百度地图 API 只支持国内的天气预报,因此像咱们这些海外党仍是须要一些其余的手段
我选择的是 Yahoo Weather API,由于很好奇他们家大名鼎鼎的 YQL ...
引入 lodash
,inquirer
, yql
这三个库
先上代码
let config = _.assign({ cityName: '' }, option) let promps = [] if(config.cityName !== 'string') { promps.push({ type: 'input', name: 'cityName', message: 'Input your cityname:', validate: input => { if(!input) { return chalk.red('You should input something here...') } return true } }) } inquirer.prompt(promps).then(answers => { var query = new YQL(`select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="${answers.cityName}")`) query.exec((err, data) => { if(err) { console.log(chalk.red('emmmmm... I don\'t know what happened.')) } else { if(!data.query.count) { console.log(chalk.red('Please... Enter the correct city name.')) } else { console.log(data) } } }) })
先来讲说 inquirer
这个库
功能简介:
- input–输入
- validate–验证
- list–列表选项
- confirm–提示
- checkbox–复选框等等
YQL
可谓是有些惊人,它能够像 SQL
那样设计,而后整合至 URL
上,确实有点奇葩
这样,咱们海外党就也可使用 happyday
了
这个很简单啦
一步一步来:
bash
中输入 npm login
登陆npm publish
一个回车键搞定(每次 publish 以前都须要改一下包的版本号,否则报错)就这样咱们就拥有了本身的第一个 npm 包
本文代码均在 https://github.com/HuangXiZhou/happyday 欢迎各位 Star
使用 happyday
:
npm i happyday -g
&& happday w
便可