Skip to content

Instantly share code, notes, and snippets.

@robynitp
Last active August 29, 2015 14:10
Show Gist options
  • Save robynitp/22d92f158a8df7bf6adf to your computer and use it in GitHub Desktop.
Save robynitp/22d92f158a8df7bf6adf to your computer and use it in GitHub Desktop.
load URL and load JSON file in servi.js
var servi = require('servi');
var app = new servi(true);
var http = require('http');
start();
route('/', showHome);
function showHome(request){
// load a local JSON file
loadJSON('weather.json',function(data){
console.log("____json from file_____");
console.log(data);
});
// load JSON from a URL
var myUrl = "http://api.openweathermap.org/data/2.5/weather?q=London,uk";
loadJSON(myUrl,function(data){
console.log("____json from url_____");
console.log(data);
});
request.respond('testing');
}
// load text from a url
function loadURL(url,onSuccess){
var str = '';
http.get(url, function(res) {
res.on("data", function(chunk) {
str += chunk.toString();
});
res.on("end",function(){
onSuccess(str);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
// use an onError() callback here?
});
}
// takes a file path or a URL
function loadJSON(path,callback){
// is it a URL ?
if (path.indexOf('http') === 0){
loadURL(path, function(res){
callback(JSON.parse(res));
});
} else { // assume it's a file
callback(JSON.parse(loadFile(path)));
}
}
{
"coord": {
"lon": -74.01,
"lat": 40.71
},
"sys": {
"type": 1,
"id": 1980,
"message": 0.115,
"country": "US",
"sunrise": 1416311222,
"sunset": 1416346537
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
},
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "50n"
},
{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle",
"icon": "09n"
}
],
"base": "cmc stations",
"main": {
"temp": 47.84,
"pressure": 1000,
"humidity": 93,
"temp_min": 42.8,
"temp_max": 57.2
},
"wind": {
"speed": 3.24,
"deg": 270
},
"clouds": {
"all": 90
},
"dt": 1416267540,
"id": 5128581,
"name": "New York",
"cod": 200
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment