我发现node-maxmind 是功能最完整且易于使用的模块。你需要从maxminddownload page下载文件,然后就可以这样使用了:
maxmind = require 'maxmind'
maxmind.init('GeoLiteCity.dat')
maxmind.getLocation('67.188.232.131')
{ countryCode: 'US',
countryName: 'United States',
region: 'CA',
city: 'Mountain View',
postalCode: '94043',
latitude: 37.41919999999999,
longitude: -122.0574,
dmaCode: 0,
areaCode: 0,
metroCode: 0,
regionName: 'California' }
使用通常需要您安装地理定位数据库并定期更新它的模块的替代方法是使用地理定位 API。我自己的服务之一是http://ipinfo.io。这是一个使用出色的请求模块调用它的示例:
request = require 'request'
request.get('http://ipinfo.io/67.188.232.131', {json: true}, (e, r) -> console.log r.body)
{ ip: '67.188.232.131',
hostname: 'c-67-188-232-131.hsd1.ca.comcast.net',
city: 'Mountain View',
region: 'California',
country: 'US',
loc: '37.4192,-122.0574',
org: 'AS7922 Comcast Cable Communications, Inc.',
postal: '94043' }
更多详情请见http://ipinfo.io/developers。