/
app.js
45 lines (38 loc) · 1009 Bytes
/
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
const https = require('https');
getCountryInfo("ESP", showErrorOrCountry);
console.log("Petición realizada");
console.log("---");
getCountryInfo("XXX", showErrorOrCountry);
console.log("Petición realizada");
console.log("---");
function getCountryInfo(code, callback) {
const url = `https://restcountries.com/v3.1/alpha/${code}`;
https
.get(url, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
if (resp.statusCode === 404){
callback(new Error("País no encontrado"));
} else {
let country = JSON.parse(data)[0];
callback(undefined, country);
}
});
})
.on("error", (err) => {
callback(err);
});
}
function showErrorOrCountry(err, country) {
if (err !== undefined) {
console.log("Error: " + err.message);
} else {
for (let key in country) {
console.log(`${key}: ${country[key]}`);
}
console.log(`\n`);
}
}