forked from davidtsai/node-geoip2
-
Notifications
You must be signed in to change notification settings - Fork 2
/
node-geoip2.js
63 lines (53 loc) · 1.62 KB
/
node-geoip2.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
var mmdb = require('./lib/node_mmdb.node');
var path = require('path');
var _defaultPath = path.resolve(__dirname, './databases/GeoLite2-City.mmdb');
var _defaultDB = null;
exports.MMDB = mmdb.MMDB;
exports.init = function(path) {
_defaultDB = new mmdb.MMDB(path || _defaultPath);
return _defaultDB;
}
exports.cleanup = function() {
_defaultDB = null;
}
exports.lookup = function(address, callback) {
if (!_defaultDB) {
console.log("WARNING: ipgeo2 database not initialized, initializing default now.");
exports.init();
}
_defaultDB.lookup(address, callback);
}
exports.lookupSync = function(address) {
if (!_defaultDB) {
console.log("WARNING: ipgeo2 database not initialized, initializing default now.");
exports.init();
}
return _defaultDB.lookupSync(address);
}
function parseResult(result) {
return {
country: result.country ? result.country.iso_code : undefined,
continent: result.continent ? result.continent.code : undefined,
postal: result.postal ? result.postal.code : undefined,
city: result.city && result.city.names ? result.city.names.en : undefined,
location: result.location,
subdivision: result.subdivisions ? result.subdivisions[0].iso_code : undefined
};
}
exports.lookupSimple = function(address, callback) {
exports.lookup(address, function(error, result) {
if (result) {
callback(null, parseResult(result));
}
else {
callback(error, null);
}
});
}
exports.lookupSimpleSync = function(address) {
var result = exports.lookupSync(address);
if (result) {
return parseResult(result);
}
return null;
}