DNS


稳定性: 2 - 稳定的

¥Stability: 2 - Stable

源代码: lib/dns.js

node:dns 模块启用了名称解析。例如,使用它来查找主机名的 IP 地址。

¥The node:dns module enables name resolution. For example, use it to look up IP addresses of host names.

虽然以 域名系统 (DNS) 命名,但它并不总是使用 DNS 协议进行查找。dns.lookup() 使用操作系统工具来执行名称解析。它可能不需要执行任何网络通信。要像同一系统上的其他应用那样执行名称解析,则使用 dns.lookup()

¥Although named for the Domain Name System (DNS), it does not always use the DNS protocol for lookups. dns.lookup() uses the operating system facilities to perform name resolution. It may not need to perform any network communication. To perform name resolution the way other applications on the same system do, use dns.lookup().

import dns from 'node:dns';

dns.lookup('example.org', (err, address, family) => {
  console.log('address: %j family: IPv%s', address, family);
});
// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6const dns = require('node:dns');

dns.lookup('example.org', (err, address, family) => {
  console.log('address: %j family: IPv%s', address, family);
});
// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6

node:dns 模块中的所有其他函数都连接到实际的域名系统服务器以执行名称解析。它们将始终使用网络来执行域名系统查询。这些函数不使用 dns.lookup() 使用的同一组配置文件(例如 /etc/hosts)。使用这些函数始终执行域名系统查询,绕过其他名称解析工具。

¥All other functions in the node:dns module connect to an actual DNS server to perform name resolution. They will always use the network to perform DNS queries. These functions do not use the same set of configuration files used by dns.lookup() (e.g. /etc/hosts). Use these functions to always perform DNS queries, bypassing other name-resolution facilities.

import dns from 'node:dns';

dns.resolve4('archive.org', (err, addresses) => {
  if (err) throw err;

  console.log(`addresses: ${JSON.stringify(addresses)}`);

  addresses.forEach((a) => {
    dns.reverse(a, (err, hostnames) => {
      if (err) {
        throw err;
      }
      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
    });
  });
});const dns = require('node:dns');

dns.resolve4('archive.org', (err, addresses) => {
  if (err) throw err;

  console.log(`addresses: ${JSON.stringify(addresses)}`);

  addresses.forEach((a) => {
    dns.reverse(a, (err, hostnames) => {
      if (err) {
        throw err;
      }
      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
    });
  });
});

有关详细信息,请参阅 实现的注意事项章节

¥See the Implementation considerations section for more information.