Skip to content

Instantly share code, notes, and snippets.

@soarez
Created September 29, 2014 08:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soarez/788e6752259ab1b42994 to your computer and use it in GitHub Desktop.
Save soarez/788e6752259ab1b42994 to your computer and use it in GitHub Desktop.
Query maxmind geolite2 country ( ISO_3166 ) downloadable db
var mmdbreader = require('maxmind-db-reader');
module.exports = Open;
function Open(dbPath) {
var db;
var queued = [];
mmdbreader.open(dbPath, dbReady);
return query;
function dbReady(err, handle) {
if (err) throw err;
db = handle;
while (queued.length)
query.apply(null, queued.shift());
}
function query(ip, cb) {
if (! db)
return queued.push(Array.prototype.slice.call(arguments));
db.getGeoData(ip, select);
function select(err, geodata) {
cb(err, !err && geodata.country.iso_code);
}
}
}
if (require.main === module) {
// Download and extract:
// http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz
var db = Open(require('path').join(__dirname, 'GeoLite2-Country.mmdb'));
db(process.argv[2] || '193.137.100.231', function(err, countryCode) {
if (err) throw err;
console.log(countryCode);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment