Skip to content

Instantly share code, notes, and snippets.

@danielronnkvist
Last active August 16, 2017 07:02
Show Gist options
  • Save danielronnkvist/4dabcb3c457e7ef4a52af652d683f929 to your computer and use it in GitHub Desktop.
Save danielronnkvist/4dabcb3c457e7ef4a52af652d683f929 to your computer and use it in GitHub Desktop.
Fetch the train position while travelling on a SJ train (and using their wifi) and store all data for further visualisations.
var http = require('http');
var fs = require('fs');
var dataFile = './data.json';
var dataURL = 'http://www.ombord.info/api/jsonp/position/';
var errorHandling = (e) => {
console.log(`Got error: ${e.message}`);
fetchData();
}
var saveData = (position) => {
return new Promise((resolve, reject) => {
fs.readFile(dataFile, (err, data) => {
if(err) reject(err);
data = JSON.parse(data);
data.push(position);
fs.writeFile(dataFile, JSON.stringify(data), (err) => {
if(err) reject(err);
console.log('data saved');
setTimeout(resolve, 1500);
});
});
});
}
var fetchData = () => {
http.get(dataURL, (res) => {
var data = '';
res.setEncoding('utf8');
res.on('data', (chunk) => data += chunk );
res.on('end', () => {
data = data.slice(1).slice(0, -3);
data = JSON.parse(data);
saveData(data).then(fetchData).catch(errorHandling);
});
}).on('error', errorHandling);
}
var startUp = () => {
try {
fs.readFileSync(dataFile);
} catch(e) {
fs.writeFileSync(dataFile, '[]');
}
fetchData();
}
startUp();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment