-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.js
88 lines (75 loc) · 2.55 KB
/
weather.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Gets the temperature and chance of precipitation for today
*
* @param location The location (lat/lng object from properties.json)
* @param callback The callback function
* @param apiKey The Forecast API key
*
* @callback The temperature in Fahrenheit and the precipitation percentage
*/
module.exports = function (location, callback, apiKey) {
try {
getJSON(
{
host: 'api.forecast.io',
port: 443,
path: '/forecast/' + apiKey + "/" + location.lat + "," + location.lng + "?exclude=currently,minutely,hourly,alerts,flags&units=us",
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
},
function (statusCode, result) {
if (statusCode != 200) {
console.log("Could not get data from Forecast API");
callback(new Error("Could not get data from Forecast API"), null, null);
}
var tempF = NaN,
precipPct = NaN;
try {
tempF = result.daily.data[0].apparentTemperatureMax;
precipPct = result.daily.data[0].precipProbability;
} catch (e) {
callback(e, null, null)
}
var cal = new Date();
var date = cal.toDateString();
var time = cal.toLocaleTimeString();
console.log("Today's forecast: Temperature: " + tempF +
" F, Precipitation: " + precipPct + "%. Retrieved " +
date + ' ' + time + '.');
callback(null, tempF, precipPct); // null for no error!
}
);
}
catch (e) {
callback(e, null, null)
}
};
var http = require("http");
var https = require("https");
/**
* Gets a JSON object over HTTP(s)
*
* @param options An object of options.
* @param onResult Callback
*/
function getJSON(options, onResult) {
var prot = options.port == 443 ? https : http;
var req = prot.request(options, function (res) {
var output = '';
//console.log(options.host + ':' + res.statusCode); //debug
res.setEncoding('utf8');
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', function () {
var obj = JSON.parse(output);
onResult(res.statusCode, obj);
});
});
req.on('error', function (err) {
throw err;
});
req.end();
}