Fetch local weather from Dark Sky API. https://wthr.ml/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.2 KiB

  1. const log = console.log
  2. const fs = require('fs')
  3. const {table, getBorderCharacters} = require('table')
  4. const argv = require('yargs').argv
  5. const TABLE_CONFIG = {
  6. // columns: {
  7. // 0: { alignment: 'center' },
  8. // 1: { alignment: 'center' },
  9. // 2: { alignment: 'center' },
  10. // },
  11. border: getBorderCharacters(`ramac`)
  12. }
  13. const CREDIT_MSG = "Powered by Dark Sky: https://darksky.net/poweredby/"
  14. // https://medium.com/@osiolabs/read-write-json-files-with-node-js-92d03cc82824
  15. const jsonReader = (filePath, cb) => {
  16. fs.readFile(filePath, (err, fileData) => {
  17. if (err) {
  18. return cb && cb(err)
  19. }
  20. try {
  21. const object = JSON.parse(fileData)
  22. return cb && cb(null, object)
  23. } catch(err) {
  24. return cb && cb(err)
  25. }
  26. })
  27. }
  28. const logWeatherJson = (jsonFile, loc) => {
  29. return new Promise((resolve, reject) => {
  30. jsonReader(jsonFile, (err, weatherInfo) => {
  31. if (err) {
  32. reject(err)
  33. }
  34. log(loc)
  35. if (argv.v) {
  36. const infoList = [['H', '°C', '%P']]
  37. for (let i = 0; i < 12; i++) {
  38. const hourInfo = weatherInfo['hourly']['data'][i]
  39. const date = new Date(hourInfo['time'] * 1000)
  40. infoList.push([date.getHours(),
  41. Math.floor(hourInfo['apparentTemperature']),
  42. Math.floor(hourInfo['precipProbability'])])
  43. }
  44. log(table(infoList, TABLE_CONFIG));
  45. } else {
  46. // horizontal
  47. const hoursList = ['H']
  48. const tempsList = ['°C']
  49. const precipList = ['%P']
  50. for (let i = 0; i < 9; i++) {
  51. const hourInfo = weatherInfo['hourly']['data'][i]
  52. const date = new Date(hourInfo['time'] * 1000)
  53. hoursList.push(date.getHours())
  54. tempsList.push(Math.floor(hourInfo['apparentTemperature']))
  55. precipList.push(Math.floor(hourInfo['precipProbability']))
  56. }
  57. log(table([hoursList, tempsList, precipList], TABLE_CONFIG));
  58. }
  59. resolve()
  60. })
  61. })
  62. }
  63. logTablePromises = [
  64. logWeatherJson('./markham.json', 'Markham'),
  65. logWeatherJson('./toronto.json', 'Toronto')]
  66. Promise.all(logTablePromises).then(results => {
  67. const now = new Date()
  68. log(`${CREDIT_MSG}\n\nLast updated: ${now.getHours()}:${now.getMinutes()}`)
  69. })