Skip to content

Instantly share code, notes, and snippets.

@arecvlohe
Last active October 15, 2015 21:42
Show Gist options
  • Save arecvlohe/ce32eda2936d1066cb68 to your computer and use it in GitHub Desktop.
Save arecvlohe/ce32eda2936d1066cb68 to your computer and use it in GitHub Desktop.
var http = require('http'),
cities = ['Tampa,FL', 'Miami,FL', 'Seattle,WA', 'NewYork,NY', 'Tulsa,OK'],
weather = [],
count = 0,
port = 3000,
tempAvg;
var cityAPIs = cities.map(function(location) {
return 'http://api.openweathermap.org/data/2.5/weather?q=' + location + '&units=imperial&appid=bd82977b86bf27fb59a04b61b657fb6f';
});
function calAvg() {
count+=1;
if(count === cities.length) {
tempAvg = weather.map(function(str) {
var data = JSON.parse(str);
return data.main.temp;
}).reduce(function(tempPrv, tempNxt) {
return tempPrv + tempNxt;
});
tempAvg = (tempAvg / cities.length + 1).toFixed(1);
}
}
function getWeather(callback) {
cityAPIs.forEach(function(url, idx, arr) {
http.get(url, function(res) {
weather[idx] = '';
res.setEncoding('utf8');
res.on('error', function(error) {
console.error(error);
});
res.on('data', function(data) {
weather[idx]+=data;
});
res.on('end', function() {
console.log('logged entry ' + idx + '\n' + weather[idx]);
callback();
});
});
});
}
getWeather(calAvg);
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type':'application/json'});
res.write('{\n\t tempAvg: ' + tempAvg + '\n}', 'utf8');
res.end();
});
server.listen(port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment