新建项目使用npminit快速生成一个package.json来新建一个npm项目:{"name":"happyday","version":"1.0.5","description":"Happyeveryday","main":"index.js","scripts":{"test":"echo\"Error:notestspecified\"&&exit1"},"keywords":["Nodejs","JavaScript","bash","shell"],"repository":{"type":"git","url":"git+https://github.com/HuangXiZhou/happyday.git"},"author":"xizhouh@gmail.com","license":"MIT"}封装脚本新建一个包含我们脚本的index.js#!/usr/bin/envnode//表示这是一个可执行的应用程序console.log('Happyeveryday!')在package.json中新建一个bin字段存放一个可执行文件"bin":{"happyday":"./index.js"}然后执行npmi-g&&npmlink将happyday字段复制到npm的全局模块安装文件夹node_modules,并创建一个符号链接(symboliclink,softlink),即将index.js的路径添加到环境变量PATH中运行happyday。可以看到我们已经成功打印Happyeveryday!,现在可以开始开发npm包,解析命令行参数,安装tjmastercommander:npmicommander-Snode.js命令行接口的完整解决方案,灵感来自于Ruby的指挥官。安装粉笔让你的命令行更漂亮:npmichalk-S下面我们写一个demo来测试一下:#!/usr/bin/envnodeconstprogram=require('commander')constchalk=require('chalk')program。command('weather')//命令行command.alias('w')//定义别名.description(chalk.green('Getweatherforecast;)'))//这行文本变成绿色~//注册一个`callback`function.action(option=>{console.log('biubiubiu~')})//生成帮助信息.on('--help',()=>{console.log('Examples:')console.log('')console.log('$happydayweather')console.log('$happydayw')})program.parse(process.argv)//解析命令行并执行happyday-hUsage:happyday[options][command]Options:-h,--help输出使用信息命令:weather|w获取天气预报;)这样第一步就完成了,我们可以正式开发我们的天气预报小玩具了.使用百度地图API获取天气预报,先在百度开发者中心注册一个KEY因为我比较懒...所以直接引入axios实现GET请求:constURL_IP='http://api.map.baidu.com/location/ip'constKEY={ak:'...'}....action(option=>{axios.get(URL_IP,{params:KEY}).then(res=>{console.log(res)}).catch(error=>{console.log(chalk.red('emmmmm...我不知道发生了什么。'))})})...先获取用户所在城市,然后根据城市获取用户所在位置的天气预报constURL_FORECAST='http://api.map.baidu.com/telematics/v3/weather'constKEY={阿克:'。..'}letgetweatherModel={location:'',output:'json',ak:KEY.ak,}...getweatherModel.location=res.data.content.address_detail.cityaxios.get(URL_FORECAST,{params:getweatherModel}).then(res=>{if(res.status!==200){console.log(chalk.red('哎呀!!!你的网络有问题。'))}else{letresource=res.dataif(resource.status!=='success'){console.log(chalk.red('emmmmm...我不知道发生了什么。'))}else{console.log(resource)}}}).catch(error=>{console.log(chalk.red('emmmmm...我不知道发生了什么。'))})...拿到数据后,我们来处理一下看看数据`City:${chalk.green(resource.results[0].currentCity)}??`打印天气预报resource.r结果[0].weather_data.forEach(item=>{console.log(`${item.date.slice(0,2)}:${chalk.green(item.weather)}|${chalk.green(item.temperature)}`)},this)这样,我们的小玩具就初步成型了。不过...百度地图API只支持国内的天气预报,所以像我们这样的海外小伙伴还是需要一些其他的方式来获取海外城市的天气预报我选择了YahooWeatherAPI,因为我很好奇他们大名鼎鼎的YQL...介绍一下lodash、inquirer、yql这三个库先来代码letconfig=_.assign({cityName:''},option)letpromps=[]if(config.cityName!=='string'){prompts.push({type:'input',name:'cityName',message:'Inputyourcityname:',validate:input=>{if(!input){returnchalk.red('你应该在这里输入一些东西...')}returntrue}})}inquirer.prompt(promps).then(answers=>{varquery=newYQL(`select*fromweather.forecastwherewoeidin(selectwoeidfromgeo.places(1)wheretext="${answers.cityName}")`)query.exec((err,data)=>{if(err){console.log(chalk.red('emmmmm...我不知道发生了什么。'))}else{如果(!data.query.count){console.log(chalk.red('请...输入正确的城市名称'))}else{console.log(data)}}})})先说查询者库函数介绍:input-inputvalidate-validationlist-listoptionconfirm-promptcheckbox-checkbox等YQL有点神奇,可以像SQL一样设计,然后集成到URL中,确实有点诡异的。这样,我们海外党也可以使用happyday来发布npm包了。这很简单。一步一步:在npm官网注册一个账号,在bash中输入npmlogin,登录npmpublish,回车即可完成(每次publish前需要更改包版本号,否则会报错报告)这样,我们就有了第一个npm包。本文代码在https://github.com/HuangXiZhou/happyday欢迎Star使用happyday:npmihappyday-g&&happydayw
