Nodejs获取当天天气信息

index.js

var http = require('http');
var URL = require('url');
var weather = require('./weather');

http.createServer(function (request, response) {
	var ip = URL.parse(request.url, true).query.ip;
	if(ip){	//有参数请求
		weather.getIpInfo(ip, function(cityinfo){
			var cityid = weather.getCityId(cityinfo[0], cityinfo[1]);
			weather.getWeatherInfo(cityid, function(weatherinfo){
				response.writeHead(200, {"Content-Type": "text/html;charset:utf-8"});
				response.write(JSON.stringify(weatherinfo));
				response.end();
			});
		});
	}else{	//无参数请求
		ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress || request.socket.remoteAddress || request.connection.socket.remoteAddress;
		weather.getIpInfo(ip, function(cityinfo){
			var cityid = weather.getCityId(cityinfo[0], cityinfo[1]);
			weather.getWeatherInfo(cityid, function(weatherinfo){
				var weatherinfo = weatherinfo.weatherinfo;
				var html = "<html>" +
                                           "<head>" + 
				           "<meta charset='utf-8'/>" + 
    					   "<title>天气</title>" + 
					   "<style>*{font-family: arial, helvetica, sans-serif; font-size: 12px; color: rgb(153, 153, 153);}</style>" +
					   "</head>" + 
					   "<body>" + 
					   weatherinfo.city + ": " + 
					   weatherinfo.temp2 + "~" + weatherinfo.temp1 + " " + 
					   weatherinfo.weather + 
					   " (更新时间: " + weatherinfo.ptime + ")" + 
					   "</body>" + 
					   "</html>";
				response.writeHead(200, {"Content-Type": "text/html"});
				response.write(html);
				response.end();
			});
		});
	}
    console.log(ip);
}).listen(1081);

weather.js

var http = require('http');
var cityinfo= require('./cityid.json');

/**
 * 根据 ip 获取获取地址信息.
 */
var getIpInfo = function(ip, callback) {
    http.get("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" + ip, function(res) {
        var code = res.statusCode;
        if (code == 200) {
            res.on('data', function(data) {
            	var province = JSON.parse(data).province;
            	var city = JSON.parse(data).city;
				callback([province, city]);
            });
        }
    }).on('error', function(e) { console.log(e) });
}

/**
 * 根据城市获取城市的天气id.
 */
var getCityId = function(country, city){
	var cityid = '101010100';
	var province = cityinfo["China"].province;
	for(var i = 0; i < province.length; i++){
		if(province[i]["name"] == country){
			if(province[i]["city"][0]){
				var citys = province[i]["city"];
				for (var j = 0; j < citys.length; j++) {
					if(citys[j]["name"] == city){
						cityid = citys[j]["county"][0]["weatherCode"];
					}
				};
			}else{
				cityid = province[i]["city"]["county"][0]["weatherCode"];
			}
		}
	}
	return cityid;
}

/**
 * 获取天气数据.
 */
var getWeatherInfo = function(cityid, callback){
	http.get("http://www.weather.com.cn/data/cityinfo/" + cityid + ".html", function(res){
		res.on("data",function(data){
			data = JSON.parse(data);
			callback(data);
		});
	});	
}

exports.getIpInfo = getIpInfo;
exports.getCityId = getCityId;
exports.getWeatherInfo = getWeatherInfo;

cityid.json为城市id和天气id的关系文件

转载于:https://my.oschina.net/chenhao901007/blog/367535

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值