打开 maxmind DB 并在 nodejs 中访问它

Opening maxmind DB and accessing it in nodejs

以前我是这样使用的:

现在,根据 node 10 更新模块。 所以,需要帮助来整合它。

reference

const maxmind = require('maxmind');
exports.getIsoCountry = function(pIpAddress) {

  modules.debugLog('inside getIsoCountry : ',pIpAddress);

  maxmind.open(sGlAppVariable.maxmindDbPath)
  .then(function(lookup) {
    var ipData = lookup.get(pIpAddress);
    //console.log(ipData);
    console.log('iso_code',ipData.country.iso_code);
    return ipData.country.iso_code;
  });

}

console.log(getIsoCountry('66.6.44.4')); 它应该打印国家代码。但它总是 undefined。因为这是一个承诺。

如何调用这个getIsoCountry函数?

我们将不胜感激。

您需要等待执行完成,为此,您应该使用Promise

修改你的代码如下,然后它应该工作:

const maxmind = require('maxmind');
exports.getIsoCountry = function(pIpAddress) {
  return new Promise((resolve, reject) => {
    modules.debugLog('inside getIsoCountry : ',pIpAddress);
      maxmind.open(sGlAppVariable.maxmindDbPath)
      .then(function(lookup) {
        var ipData = lookup.get(pIpAddress);
        console.log('iso_code',ipData.country.iso_code);
        resolve(ipData.country.iso_code);
      });
  });
}

getIsoCountry("66.6.44.4").then((rData) => {
  console.log(rData)
});

示例代码如下:

var getIsoCountry = function(pIpAddress) {

  return maxmind().then(function() {
       return "Code for IP: " + pIpAddress;
    });

  function maxmind() {
    return new Promise((resolve, reject) => {
      resolve("done")
    });
  }

}

getIsoCountry("1.1.1.1").then((data) => {
  console.log(data)
});