Created
November 12, 2016 07:30
-
-
Save jtinfors/c1e08b107dfa3744a5582ab5bdad548d to your computer and use it in GitHub Desktop.
A tiny script to convert timeline data to csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const argv = require('minimist')(process.argv.slice(2)) | |
const request = require('request') | |
const fs = require('fs') | |
const FILE_NAME = 'timedata.csv' | |
if (!argv.token || !argv.apikey || !argv.thingid) { | |
console.error(`Missing arg(s).\n\tUsage: ${process.argv[1]} --thingid <thingid> --apikey <key> --token <token> [--days <days>]\n`) | |
process.exit(1) | |
} | |
let days = argv.days || 10 | |
request({ | |
url: `https://next.fairtrail.me/v1/timeseries/${argv.thingid}?time=${days}d`, | |
json: true, | |
headers: { | |
'apikey': argv.apikey, | |
'authorization': `token ${argv.token}` | |
} | |
}, (err, res, body) => { | |
if (err) { | |
console.error(err) | |
return process.exit(1) | |
} | |
if (res.statusCode !== 200) { | |
console.error(`Got statusCode ${res.statusCode} back from server. Exiting`) | |
return process.exit(1) | |
} | |
let data = body.time.reduce((memo, time, index, array) => { | |
let item = `"${time}", "${body.hum[index]}", "${body.temp[index]}"` | |
item = index < array.length ? item + '\n' : item | |
memo += item | |
return memo | |
}, '"time", "hum", "temp"\n') | |
fs.writeFile(`./${FILE_NAME}`, data, 'utf8', (err) => { | |
if (err) { console.err(err); return process.exit(1) } | |
return console.log(`>>> ${FILE_NAME}`) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment