Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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