-
Notifications
You must be signed in to change notification settings - Fork 1
/
geo.js
executable file
·68 lines (54 loc) · 1.59 KB
/
geo.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
66
67
68
var http = require('http')
require('dotenv').config()
function Geo(options) {
var self = this;
function request(options, callback)
{
http.get(options.host, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var response = JSON.parse(body);
console.log("Got a response: ", response);
callback(null, response);
});
}).on('error', function(e){
console.error("Got an error: ", e);
});
}
function extract_geo(response) {
var countryString;
if(response["city"] == "") {
countryString = response["country_name"];
} else {
countryString = response["city"] + ", " + response["country_name"];
}
var o = {
country : countryString,
img : "https://geoiptool.com/static/img/flags/" + response["country_code"].toLowerCase() + ".gif"
}
return o;
}
self.get = function(ip, callback) {
// console.log("QUERYING IP:",ip);
var options = {
host : 'http://api.ipstack.com/'+ip+'?access_key=' + process.env.API_KEY + '&output=json&legacy=1',
port : 80,
method: 'GET'
}
request(options, function(err, response) {
if(err)
return callback(err);
var geo = null;
try {
var geo = extract_geo(response);
} catch(ex) {
console.error(ex);
}
return callback(null, geo);
}, true);
}
}
module.exports = Geo;