📜  Node.js DNS(1)

📅  最后修改于: 2023-12-03 15:03:12.578000             🧑  作者: Mango

Node.js DNS

Node.js DNS module provides a way to do various DNS lookups such as IPv4, IPv6, MX, TXT, etc. It is a built-in module in Node.js, so no external module needs to be installed for it.

Methods
dns.lookup()

This method is used to resolve a domain name into an IP address. It takes three arguments: hostname, options, and callback.

const dns = require('dns');

dns.lookup('google.com', (err, address) => {
  console.log(address);
  // Prints: 172.217.4.142
});
dns.resolve()

This method is used to resolve a domain name into an array of the specified record types. It takes four arguments: hostname, rrtype, callback, and options.

const dns = require('dns');

dns.resolve('google.com', 'MX', (err, addresses) => {
  console.log(addresses);
  // Prints: [ { exchange: 'alt1.aspmx.l.google.com', priority: 10 },
  //           { exchange: 'alt2.aspmx.l.google.com', priority: 20 },
  //           { exchange: 'alt3.aspmx.l.google.com', priority: 30 },
  //           { exchange: 'alt4.aspmx.l.google.com', priority: 40 },
  //           { exchange: 'aspmx.l.google.com', priority: 5 } ]
});
dns.resolveTxt()

This method is used to resolve a domain name into an array of the TXT records. It takes two arguments: hostname and callback.

const dns = require('dns');

dns.resolveTxt('google.com', (err, addresses) => {
  console.log(addresses);
  // Prints: [ [ 'v=spf1 include:_spf.google.com ~all' ] ]
});
dns.reverse()

This method is used to resolve an IP address into an array of domain names. It takes two arguments: ip and callback.

const dns = require('dns');

dns.reverse('172.217.4.142', (err, hostnames) => {
  console.log(hostnames);
  // Prints: [ 'ord38s02-in-f142.1e100.net' ]
});
Conclusion

The Node.js DNS module provides various methods to resolve domain names and IP addresses. Developers can use this module to build network-based applications.