-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
65 lines (59 loc) · 1.82 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
require("dotenv").config({
path: 'variables.env'
});
const fs = require('fs');
const yargs = require('yargs');
const axios = require('axios');
let argv = yargs
.options({
a: {
describe: "Address to fetch Weather for",
demand: false,
alias: 'address',
string: true
},
d: {
describe: "Set default address",
demand: false,
alias: 'setdefault',
string: true
}
})
.help()
.alias('help', 'h')
.argv;
if (argv.setdefault) {
fs.writeFileSync("defaultAddress.txt", argv.setdefault);
}
if (!argv.address) {
try {
argv.address = fs.readFileSync("defaultAddress.txt");
} catch (e) {
console.log("Please provide an address. \n");
yargs.showHelp();
process.exit();
}
}
let encodedAddress = encodeURIComponent(argv.address);
let url= `https://nominatim.openstreetmap.org/search.php?q=${encodedAddress}&format=json`;
axios.get(url)
.then((response) => {
if (response.data.length === 0) {
throw new Error("Unable to find that address.");
}
let lat = response.data[0].lat;
let long = response.data[0].lon;
let weatherUrl = `https://api.darksky.net/forecast/${process.env.API_KEY}/${lat},${long}`;
console.log(response.data[0].display_name);
return axios.get(weatherUrl);
})
.then((response) => {
console.log(`It's currently ${response.data.currently.summary}. The current temperature is ${response.data.currently.temperature}. It feels like ${response.data.currently.apparentTemperature}.`);
})
.catch((e) => {
if (e.code === 'ENOTFOUND') {
console.log("Unable to connect to API server");
} else {
console.log(e.message);
}
});