首页 > 编程语言 >ip2region 在nodejs中的使用

ip2region 在nodejs中的使用

时间:2023-03-09 21:34:53浏览次数:53  
标签:searcher ip2region const Searcher nodejs 使用 data

ip2region 在nodejs中的使用

ip2region v2.0 - 是一个离线IP地址定位库和IP定位数据管理框架,10微秒级别的查询效率,提供了众多主流编程语言的 xdb 数据生成和查询客户端实现。

在项目中使用

1.下载ip2region模块导入到项目中

不使用这个:

npm i ip2region --save

npm命令安装的ip2region模块似乎是基于typescript语法,使用import导入包。而nodejs采用的是CommonJS的模块化规范,不支持import语句,安装其他支持插件又更加繁琐,因此本文迁移ip2region在gitee上的仓库项目,gitee仓库里的项目和示例代码都是基于JS和CommonJS的模块化规范的。

copy ip2region仓库项目,gitee url:https://gitee.com/lionsoul/ip2region

精简后的项目目录:

image

从上至下依次为:

index.js ==> 导入包文件

ReadMe.md ==> 示例代码(客户端三种查询方式实现)

/data/ip2region.xdb ==> ip2region数据文件

2.使用README.md中的示例代码

// 导入包
const Searcher = require('.')
// 指定ip2region数据文件路径
const dbPath = 'ip2region.xdb file path'

try {
  // 创建searcher对象
  const searcher = Searcher.newWithFileOnly(dbPath)
  // 查询
  const data = await searcher.search('218.4.167.70')
  // data: {region: '中国|0|江苏省|苏州市|电信', ioCount: 3, took: 1.342389}
} catch(e) {
  console.log(e)
}

官方提供的示例代码如上,包和数据文件的路径需要补充,值得注意的是ip2region的查询语句使用的是await异步方法,因此try catch外层还因有async函数包裹。完整代码如下:

// 导入包
const Searcher = require('./ip2region-master/binding/nodejs/index')
// 指定ip2region数据文件路径
const dbPath = './ip2region-master/data/ip2region.xdb'
async function test(ip){
    try {
        // 同步读取vectorIndex
        const vectorIndex = Searcher.loadVectorIndexFromFile(dbPath)
        // 创建searcher对象
        const searcher = Searcher.newWithVectorIndex(dbPath, vectorIndex)
        // 查询 await 或 promise均可
        const data = await searcher.search(ip)
        console.log(data)
        // data: {region: '中国|0|江苏省|苏州市|电信', ioCount: 2, took: 0.402874}
      } catch(e) {
        console.log(e)
      }
}
let ip = '218.4.167.70'
test(ip)

3.成功获取

在node项目中运行该脚本文件,成功获取数据。

image

标签:searcher,ip2region,const,Searcher,nodejs,使用,data
From: https://www.cnblogs.com/yuanjiejie/p/17201517.html

相关文章