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的关系文件