update nodejs client

This commit is contained in:
dongyado 2016-07-06 00:29:19 +08:00
parent b187d1646a
commit 0fb5af9067
2 changed files with 55 additions and 27 deletions

View File

@ -6,29 +6,59 @@
* @author dongyado<dongyado@gmail.com> * @author dongyado<dongyado@gmail.com>
* */ * */
function Ip2region(db_path)
{
var fs = require('fs'); var fs = require('fs');
var ipbase = [16777216, 65536, 256, 1]; // for ip2long
var ip2r = {}; var ip2r = {};
ip2r.db_file = null; ip2r.db_file_path = null;
ip2r.db_fd = null; ip2r.db_fd = null;
// db file check
exports.setDbFile = function(path) if (typeof(db_path) == "undefined" || fs.exists(db_path) ) {
{ throw("[ip2region] db file not exists : " + db_path);
ip2r.db_file = path;
ip2r.db_fd = fs.open(ip2r.db_file);
} }
exports.getDbFile = function(path) ip2r.db_file_path = db_path;
{
return ip2r.db_file; try {
ip2r.db_fd = fs.openSync(ip2r.db_file_path, 'r');
} catch(e) {
throw("[ip2region] Can not open ip2region.db file , path : " + ip2r.db_file_path);
} }
exports.binarySearch = function(ip)
this.binarySearch = function(ip)
{ {
return ip; var buffer = new Buffer(8);
fs.readSync(ip2r.db_fd, buffer, 0, 8, 0);
console.log(buffer[0]);
return ip2long(ip);
} }
exports.btreeSearch = function(ip) this.btreeSearch = function(ip)
{ {
return ip; return ip2long(ip);
} }
function ip2long(ip)
{
var val = 0;
ip.split('.').forEach(function(ele, i){
val += ipbase[i] * ele;
});
return val;
}
function getLong(buffer)
{
}
}
module.exports = Ip2region;

View File

@ -2,9 +2,7 @@
* test program * test program
* */ * */
var ip2r = require('./ip2region'); var Ip2region = require('./ip2region');
var ip2region = new Ip2region('../../data/ip2region.db');
ip2r.setDbFile('./ip2region.db'); console.log(ip2region.binarySearch("114.114.114.114"));
console.log(ip2r.getDbFile());
console.log(ip2r.binarySearch("12321231"));