Node.js v18.12.1 documentation


Table of contents

DNS#

Stability: 2 - Stable

Source Code: lib/dns.js

The node:dns module enables name resolution. node:dns模块启用名称解析。For example, use it to look up IP addresses of host names.例如,使用它查找主机名的IP地址。

Although named for the Domain Name System (DNS), it does not always use the DNS protocol for lookups. 虽然以域名系统(DNS)命名,但它并不总是使用DNS协议进行查找。dns.lookup() uses the operating system facilities to perform name resolution. dns.lookup()使用操作系统工具执行名称解析。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().要像同一系统上的其他应用程序一样执行名称解析,请使用dns.lookup()

const dns = require('node:dns');

dns.lookup('example.org', (err, address, family) => {
console.log('address: %j family: IPv%s', address, family);
});
// address: "93.184.216.34" family: IPv4

All other functions in the node:dns module connect to an actual DNS server to perform name resolution. node:dns模块中的所有其他功能都连接到实际的dns服务器以执行名称解析。They will always use the network to perform DNS queries. 他们将始终使用网络执行DNS查询。These functions do not use the same set of configuration files used by dns.lookup() (e.g. /etc/hosts). 这些函数不使用dns.lookup()使用的同一组配置文件(例如/etc/hosts)。Use these functions to always perform DNS queries, bypassing other name-resolution facilities.使用这些函数可以始终执行DNS查询,绕过其他名称解析功能。

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.有关更多信息,请参阅实施注意事项部分