node.js 中是否有 nslookup 命令的等效功能?

Is there an equivalent function of nslookup command in node.js?

在node.js中是否有nslookup的等效功能?

下面是 nslookup 命令在我的 MacBook Pro 上的执行结果:

> nslookup www.amagicshop.com.tw 8.8.8.8
Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
www.amagicshop.com.tw   canonical name = s16959.dname.91app.io.
s16959.dname.91app.io   canonical name = proxy.letssl.91app.io.
proxy.letssl.91app.io   canonical name = proxy-letssl-91app-io-196811564.ap-northeast-1.elb.amazonaws.com.
Name:   proxy-letssl-91app-io-196811564.ap-northeast-1.elb.amazonaws.com
Address: 54.178.248.57
Name:   proxy-letssl-91app-io-196811564.ap-northeast-1.elb.amazonaws.com
Address: 52.196.80.17

我想知道 node.js 中是否有一个函数,给定 www.amagicshop.com.tw8.8.8.8 作为输入,还有 returns
s16959.dname.91app.io., proxy.letssl.91app.io.proxy-letssl-91app-io-196811564.ap-northeast-1.elb.amazonaws.com.52.196.80.1754.178.248.57 作为输出。

本来以为dns.resolveAny是node.js中nslookup的等价函数。但是我错了

因为下面的代码returns Error: queryAny ESERVFAIL www.amagicshop.com.tw错误.

const { Resolver } = require('dns')
const resolver = new Resolver()
resolver.setServers(['8.8.8.8'])

resolver.resolveAny('www.amagicshop.com.tw', (err, result) => {
  if (err) {
    console.error(`error: ${err}`)
  } else {
    console.log(`result:  ${JSON.stringify(result)}`)
  }
})

结果与nslookup的结果不同。

也许我必须实现一个结合 resolveCnameresolve4 的功能,这样我才能实现我想要的。

为了获得所有规范名称,我们必须递归调用(在 nslookup 中,定义也是递归的!)。

CNAME

const dns = require('dns')

let accum = []
const getCnames = (err, result) => {
  if (err) {
    // no more records
    console.log(accum)
    return accum
  } else {
    const cname = result[0]
    accum.push(cname)
    return dns.resolveCname(cname, getCnames)
  }
}

dns.resolveCname('www.amagicshop.com.tw', getCnames)

输出

[ 's16959.dname.91app.io',
  'proxy.letssl.91app.io',
  'proxy-letssl-91app-io-196811564.ap-northeast-1.elb.amazonaws.com' ]

IP 地址

dns.resolve('www.amagicshop.com.tw', callback=(err, result) => {

if (err) {
    console.error(`error: ${err}`)
  } else {
    console.log(result)
  }
})

输出

[ '52.196.80.17', '54.178.248.57' ]

合并

const dns = require('dns')

const resolve = (cname) => {
  const getIp = (accum) =>
    dns.resolve(cname,
      callback=(err, result) => {
        if (err) {
            console.error(`error: ${err}`)
          } else {
            result.push.apply(result, accum)
            console.log(result)
          }
      })

  let accum = []
  const getCnames = (err, result) => {
    if (err) {
      // no more records
      getIp(accum)
    } else {
      const cname = result[0]
      accum.push(cname)
      dns.resolveCname(cname, getCnames)
    }
  }

  dns.resolveCname(cname, getCnames)
}

resolve('www.amagicshop.com.tw')

输出

[ '52.196.80.17',
  '54.178.248.57',
  's16959.dname.91app.io',
  'proxy.letssl.91app.io',
  'proxy-letssl-91app-io-196811564.ap-northeast-1.elb.amazonaws.com' ]