- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
Node.js v20.18.0 文档
- Node.js v20.18.0
-
目录
- DNS
- 类:
dns.Resolver
dns.getServers()
dns.lookup(hostname[, options], callback)
dns.lookupService(address, port, callback)
dns.resolve(hostname[, rrtype], callback)
dns.resolve4(hostname[, options], callback)
dns.resolve6(hostname[, options], callback)
dns.resolveAny(hostname, callback)
dns.resolveCname(hostname, callback)
dns.resolveCaa(hostname, callback)
dns.resolveMx(hostname, callback)
dns.resolveNaptr(hostname, callback)
dns.resolveNs(hostname, callback)
dns.resolvePtr(hostname, callback)
dns.resolveSoa(hostname, callback)
dns.resolveSrv(hostname, callback)
dns.resolveTxt(hostname, callback)
dns.reverse(ip, callback)
dns.setDefaultResultOrder(order)
dns.getDefaultResultOrder()
dns.setServers(servers)
- DNS promise API
- 类:
dnsPromises.Resolver
resolver.cancel()
dnsPromises.getServers()
dnsPromises.lookup(hostname[, options])
dnsPromises.lookupService(address, port)
dnsPromises.resolve(hostname[, rrtype])
dnsPromises.resolve4(hostname[, options])
dnsPromises.resolve6(hostname[, options])
dnsPromises.resolveAny(hostname)
dnsPromises.resolveCaa(hostname)
dnsPromises.resolveCname(hostname)
dnsPromises.resolveMx(hostname)
dnsPromises.resolveNaptr(hostname)
dnsPromises.resolveNs(hostname)
dnsPromises.resolvePtr(hostname)
dnsPromises.resolveSoa(hostname)
dnsPromises.resolveSrv(hostname)
dnsPromises.resolveTxt(hostname)
dnsPromises.reverse(ip)
dnsPromises.setDefaultResultOrder(order)
dnsPromises.getDefaultResultOrder()
dnsPromises.setServers(servers)
- 类:
- 错误代码
- 实现的注意事项
- 类:
- DNS
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- 其他版本
DNS#
¥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: IPv6
const 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.
类:dns.Resolver
#
¥Class: dns.Resolver
域名系统请求的独立解析器。
¥An independent resolver for DNS requests.
创建新的解析器使用默认的服务器设置。使用 resolver.setServers()
设置用于解析器的服务器不会影响其他解析器:
¥Creating a new resolver uses the default server settings. Setting
the servers used for a resolver using
resolver.setServers()
does not affect
other resolvers:
import { Resolver } from 'node:dns';
const resolver = new Resolver();
resolver.setServers(['4.4.4.4']);
// This request will use the server at 4.4.4.4, independent of global settings.
resolver.resolve4('example.org', (err, addresses) => {
// ...
});
const { Resolver } = require('node:dns');
const resolver = new Resolver();
resolver.setServers(['4.4.4.4']);
// This request will use the server at 4.4.4.4, independent of global settings.
resolver.resolve4('example.org', (err, addresses) => {
// ...
});
可以使用 node:dns
模块中的以下方法:
¥The following methods from the node:dns
module are available:
Resolver([options])
#
创建新的解析器。
¥Create a new resolver.
-
options
<Object>
resolver.cancel()
#
取消此解析器进行的所有未完成的域名系统查询。相应的回调将被调用,错误码为 ECANCELLED
。
¥Cancel all outstanding DNS queries made by this resolver. The corresponding
callbacks will be called with an error with code ECANCELLED
.
resolver.setLocalAddress([ipv4][, ipv6])
#
-
ipv4
<string> IPv4 地址的字符串表示形式。默认值:'0.0.0.0'
¥
ipv4
<string> A string representation of an IPv4 address. Default:'0.0.0.0'
-
ipv6
<string> IPv6 地址的字符串表示形式。默认值:'::0'
¥
ipv6
<string> A string representation of an IPv6 address. Default:'::0'
解析器实例将从指定的 IP 地址发送其请求。这允许程序在多宿主系统上使用时指定出站接口。
¥The resolver instance will send its requests from the specified IP address. This allows programs to specify outbound interfaces when used on multi-homed systems.
如果没有指定 v4 或 v6 地址,则设置为默认值,操作系统会自动选择本地地址。
¥If a v4 or v6 address is not specified, it is set to the default and the operating system will choose a local address automatically.
解析器在向 IPv4 域名系统服务器触发请求时将使用 v4 本地地址,在向 IPv6 域名系统服务器触发请求时将使用 v6 本地地址。解析请求的 rrtype
对使用的本地地址没有影响。
¥The resolver will use the v4 local address when making requests to IPv4 DNS
servers, and the v6 local address when making requests to IPv6 DNS servers.
The rrtype
of resolution requests has no impact on the local address used.
dns.getServers()
#
-
返回:<string[]>
¥Returns: <string[]>
返回 IP 地址字符串数组,格式根据 RFC 5952,当前配置为 DNS 解析。如果使用自定义端口,则字符串将包含端口部分。
¥Returns an array of IP address strings, formatted according to RFC 5952, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.
[
'8.8.8.8',
'2001:4860:4860::8888',
'8.8.8.8:1053',
'[2001:4860:4860::8888]:1053',
]
dns.lookup(hostname[, options], callback)
#
-
hostname
<string> -
-
family
<integer> | <string> 记录族。必须是4
、6
或0
。出于向后兼容的原因,'IPv4'
和'IPv6'
分别被解释为4
和6
。值0
指示返回 IPv4 或 IPv6 地址。如果值0
与{ all: true }
一起使用(见下文),则返回 IPv4 和 IPv6 地址之一或两者,具体取决于系统的 DNS 解析器。默认值:0
。¥
family
<integer> | <string> The record family. Must be4
,6
, or0
. For backward compatibility reasons,'IPv4'
and'IPv6'
are interpreted as4
and6
respectively. The value0
indicates that either an IPv4 or IPv6 address is returned. If the value0
is used with{ all: true }
(see below), either one of or both IPv4 and IPv6 addresses are returned, depending on the system's DNS resolver. Default:0
. -
hints
<number> 一个或多个 支持的getaddrinfo
标志。多个标志可以通过按位OR
其值来传入。¥
hints
<number> One or more supportedgetaddrinfo
flags. Multiple flags may be passed by bitwiseOR
ing their values. -
all
<boolean> 当为true
时,回调返回数组中所有已解析的地址。否则,返回单个地址。默认值:false
。¥
all
<boolean> Whentrue
, the callback returns all resolved addresses in an array. Otherwise, returns a single address. Default:false
. -
order
<string> 当verbatim
时,解析的地址未排序地返回。当ipv4first
时,解析的地址按将 IPv4 地址置于 IPv6 地址之前的方式排序。当ipv6first
时,解析的地址通过将 IPv6 地址置于 IPv4 地址之前进行排序。默认值:verbatim
(地址未重新排序)。默认值可使用dns.setDefaultResultOrder()
或--dns-result-order
进行配置。¥
order
<string> Whenverbatim
, the resolved addresses are return unsorted. Whenipv4first
, the resolved addresses are sorted by placing IPv4 addresses before IPv6 addresses. Whenipv6first
, the resolved addresses are sorted by placing IPv6 addresses before IPv4 addresses. Default:verbatim
(addresses are not reordered). Default value is configurable usingdns.setDefaultResultOrder()
or--dns-result-order
. -
verbatim
<boolean> 当为true
时,回调按照 DNS 解析器返回的顺序接收 IPv4 和 IPv6 地址。当为false
时,IPv4 地址位于 IPv6 地址之前。此选项将被弃用,取而代之的是order
。当两者都指定时,order
具有更高的优先级。新代码应仅使用order
。默认值:true
(地址未重新排序)。默认值可使用dns.setDefaultResultOrder()
或--dns-result-order
进行配置。¥
verbatim
<boolean> Whentrue
, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. Whenfalse
, IPv4 addresses are placed before IPv6 addresses. This option will be deprecated in favor oforder
. When both are specified,order
has higher precedence. New code should only useorder
. Default:true
(addresses are not reordered). Default value is configurable usingdns.setDefaultResultOrder()
or--dns-result-order
.
-
-
callback
<Function>-
err
<Error> -
address
<string> IPv4 或 IPv6 地址的字符串表示形式。¥
address
<string> A string representation of an IPv4 or IPv6 address. -
family
<integer>4
或6
,表示address
族,如果地址不是 IPv4 或 IPv6 地址,则表示为0
。0
可能是操作系统使用的名称解析服务中存在错误的指示符。¥
family
<integer>4
or6
, denoting the family ofaddress
, or0
if the address is not an IPv4 or IPv6 address.0
is a likely indicator of a bug in the name resolution service used by the operating system.
-
将主机名(例如 'nodejs.org'
)解析为第一个找到的 A (IPv4) 或 AAAA (IPv6) 记录。所有 option
属性都是可选的。如果 options
是整数,则它必须是 4
或 6
– 如果未提供 options
,则返回 IPv4 或 IPv6 地址,或两者(如果找到)。
¥Resolves a host name (e.g. 'nodejs.org'
) into the first found A (IPv4) or
AAAA (IPv6) record. All option
properties are optional. If options
is an
integer, then it must be 4
or 6
– if options
is not provided, then
either IPv4 or IPv6 addresses, or both, are returned if found.
将 all
选项设置为 true
,callback
的参数更改为 (err, addresses)
,addresses
是具有属性 address
和 family
的对象数组。
¥With the all
option set to true
, the arguments for callback
change to
(err, addresses)
, with addresses
being an array of objects with the
properties address
and family
.
出错时,err
是 Error
对象,其中 err.code
是错误码。记住,err.code
将设置为 'ENOTFOUND'
,不仅当主机名不存在时,而且当查找以其他方式失败时,例如没有可用的文件描述符。
¥On error, err
is an Error
object, where err.code
is the error code.
Keep in mind that err.code
will be set to 'ENOTFOUND'
not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.
dns.lookup()
不一定与域名系统协议有任何关系。该实现使用一种操作系统工具,可以将名称与地址关联起来,反之亦然。这种实现会对任何 Node.js 程序的行为产生微妙但重要的影响。在使用 dns.lookup()
之前,请花一些时间查阅 实现的注意事项章节。
¥dns.lookup()
does not necessarily have anything to do with the DNS protocol.
The implementation uses an operating system facility that can associate names
with addresses and vice versa. This implementation can have subtle but
important consequences on the behavior of any Node.js program. Please take some
time to consult the Implementation considerations section before using
dns.lookup()
.
用法示例:
¥Example usage:
import dns from 'node:dns';
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dns.lookup('example.org', options, (err, address, family) =>
console.log('address: %j family: IPv%s', address, family));
// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6
// When options.all is true, the result will be an Array.
options.all = true;
dns.lookup('example.org', options, (err, addresses) =>
console.log('addresses: %j', addresses));
// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]
const dns = require('node:dns');
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dns.lookup('example.org', options, (err, address, family) =>
console.log('address: %j family: IPv%s', address, family));
// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6
// When options.all is true, the result will be an Array.
options.all = true;
dns.lookup('example.org', options, (err, addresses) =>
console.log('addresses: %j', addresses));
// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]
如果此方法作为其 util.promisify()
版本被调用,并且 all
未设置为 true
,则它为具有 address
和 family
属性的 Object
返回 Promise
。
¥If this method is invoked as its util.promisify()
ed version, and all
is not set to true
, it returns a Promise
for an Object
with address
and
family
properties.
支持的 getaddrinfo 标志#
¥Supported getaddrinfo flags
以下标志可以作为提示传给 dns.lookup()
。
¥The following flags can be passed as hints to dns.lookup()
.
-
dns.ADDRCONFIG
:将返回的地址类型限制为系统上配置的非环回地址类型。例如,仅当当前系统至少配置了一个 IPv4 地址时,才会返回 IPv4 地址。¥
dns.ADDRCONFIG
: Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are only returned if the current system has at least one IPv4 address configured. -
dns.V4MAPPED
:如果指定了 IPv6 族,但未找到 IPv6 地址,则返回 IPv4 映射的 IPv6 地址。某些操作系统(例如 FreeBSD 10.1)不支持它。¥
dns.V4MAPPED
: If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported on some operating systems (e.g. FreeBSD 10.1). -
dns.ALL
:如果指定了dns.V4MAPPED
,则返回解析的 IPv6 地址以及 IPv4 映射的 IPv6 地址。¥
dns.ALL
: Ifdns.V4MAPPED
is specified, return resolved IPv6 addresses as well as IPv4 mapped IPv6 addresses.
dns.lookupService(address, port, callback)
#
-
address
<string> -
port
<number> -
callback
<Function>
使用操作系统的底层 getnameinfo
实现将给定的 address
和 port
解析为主机名和服务。
¥Resolves the given address
and port
into a host name and service using
the operating system's underlying getnameinfo
implementation.
如果 address
不是有效的 IP 地址,则会抛出 TypeError
。port
将被强制为数字。如果不是合法的端口,则会抛出 TypeError
。
¥If address
is not a valid IP address, a TypeError
will be thrown.
The port
will be coerced to a number. If it is not a legal port, a TypeError
will be thrown.
出错时,err
是 Error
对象,其中 err.code
是错误码。
¥On an error, err
is an Error
object, where err.code
is the error code.
import dns from 'node:dns';
dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
console.log(hostname, service);
// Prints: localhost ssh
});
const dns = require('node:dns');
dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
console.log(hostname, service);
// Prints: localhost ssh
});
如果此方法作为其 util.promisify()
版本被调用,则其将为具有 hostname
和 service
属性的 Object
返回 Promise
。
¥If this method is invoked as its util.promisify()
ed version, it returns a
Promise
for an Object
with hostname
and service
properties.
dns.resolve(hostname[, rrtype], callback)
#
-
hostname
<string> 要解析的主机名。¥
hostname
<string> Host name to resolve. -
rrtype
<string> 资源记录类型。默认值:'A'
。¥
rrtype
<string> Resource record type. Default:'A'
. -
callback
<Function>-
err
<Error> -
records
<string[]> | <Object[]> | <Object>
-
使用域名系统协议将主机名(例如 'nodejs.org'
)解析为资源记录数组。callback
函数有参数 (err, records)
。当成功时,records
将是资源记录数组。个别结果的类型和结构因 rrtype
而异:
¥Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org'
) into an array
of the resource records. The callback
function has arguments
(err, records)
. When successful, records
will be an array of resource
records. The type and structure of individual results varies based on rrtype
:
rrtype | records 包含 | 结果类型 | 速记法 |
---|---|---|---|
'A' | IPv4 地址(默认) | <string> | dns.resolve4() |
'AAAA' | IPv6 地址 | <string> | dns.resolve6() |
'ANY' | 任何记录 | <Object> | dns.resolveAny() |
'CAA' | CA 授权记录 | <Object> | dns.resolveCaa() |
'CNAME' | 规范名称记录 | <string> | dns.resolveCname() |
'MX' | 邮件交换记录 | <Object> | dns.resolveMx() |
'NAPTR' | 名称权限指针记录 | <Object> | dns.resolveNaptr() |
'NS' | 名称服务器记录 | <string> | dns.resolveNs() |
'PTR' | 指针记录 | <string> | dns.resolvePtr() |
'SOA' | 权限记录的开始 | <Object> | dns.resolveSoa() |
'SRV' | 服务记录 | <Object> | dns.resolveSrv() |
'TXT' | 文本记录 | <string[]> | dns.resolveTxt() |
出错时,err
是一个 Error
对象,其中 err.code
是 DNS 错误代码 之一。
¥On error, err
is an Error
object, where err.code
is one of the
DNS error codes.
dns.resolve4(hostname[, options], callback)
#
-
hostname
<string> 要解析的主机名。¥
hostname
<string> Host name to resolve. -
options
<Object>-
ttl
<boolean> 检索每条记录的生存时间值 (TTL)。当为true
时,回调接收{ address: '1.2.3.4', ttl: 60 }
对象数组而不是字符串数组,TTL 以秒表示。¥
ttl
<boolean> Retrieves the Time-To-Live value (TTL) of each record. Whentrue
, the callback receives an array of{ address: '1.2.3.4', ttl: 60 }
objects rather than an array of strings, with the TTL expressed in seconds.
-
-
callback
<Function>-
err
<Error> -
addresses
<string[]> | <Object[]>
-
使用域名系统协议为 hostname
解析 IPv4 地址(A
记录)。传给 callback
函数的 addresses
参数将包含 IPv4 地址的数组(例如 ['74.125.79.104', '74.125.79.105', '74.125.79.106']
)。
¥Uses the DNS protocol to resolve a IPv4 addresses (A
records) for the
hostname
. The addresses
argument passed to the callback
function
will contain an array of IPv4 addresses (e.g.
['74.125.79.104', '74.125.79.105', '74.125.79.106']
).
dns.resolve6(hostname[, options], callback)
#
-
hostname
<string> 要解析的主机名。¥
hostname
<string> Host name to resolve. -
options
<Object>-
ttl
<boolean> 检索每条记录的生存时间值 (TTL)。当为true
时,回调接收{ address: '0:1:2:3:4:5:6:7', ttl: 60 }
对象数组而不是字符串数组,TTL 以秒表示。¥
ttl
<boolean> Retrieve the Time-To-Live value (TTL) of each record. Whentrue
, the callback receives an array of{ address: '0:1:2:3:4:5:6:7', ttl: 60 }
objects rather than an array of strings, with the TTL expressed in seconds.
-
-
callback
<Function>-
err
<Error> -
addresses
<string[]> | <Object[]>
-
使用域名系统协议为 hostname
解析 IPv6 地址(AAAA
记录)。传给 callback
函数的 addresses
参数将包含 IPv6 地址数组。
¥Uses the DNS protocol to resolve IPv6 addresses (AAAA
records) for the
hostname
. The addresses
argument passed to the callback
function
will contain an array of IPv6 addresses.
dns.resolveAny(hostname, callback)
#
-
hostname
<string> -
callback
<Function>-
err
<Error> -
ret
<Object[]>
-
使用域名系统协议解析所有记录(也称为 ANY
或 *
查询)。传给 callback
函数的 ret
参数将是包含各种类型记录的数组。每个对象都有表示当前记录的类型的属性 type
。并且根据 type
,对象上将出现其他属性:
¥Uses the DNS protocol to resolve all records (also known as ANY
or *
query).
The ret
argument passed to the callback
function will be an array containing
various types of records. Each object has a property type
that indicates the
type of the current record. And depending on the type
, additional properties
will be present on the object:
类型 | 属性 |
---|---|
'A' | address /ttl |
'AAAA' | address /ttl |
'CNAME' | value |
'MX' | 参考 dns.resolveMx() |
'NAPTR' | 参考 dns.resolveNaptr() |
'NS' | value |
'PTR' | value |
'SOA' | 参考 dns.resolveSoa() |
'SRV' | 参考 dns.resolveSrv() |
'TXT' | 这种类型的记录包含一个名为 entries 的数组属性,它引用 dns.resolveTxt() ,例如 { entries: ['...'], type: 'TXT' } |
这是传给回调的 ret
对象的示例:
¥Here is an example of the ret
object passed to the callback:
[ { type: 'A', address: '127.0.0.1', ttl: 299 },
{ type: 'CNAME', value: 'example.com' },
{ type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
{ type: 'NS', value: 'ns1.example.com' },
{ type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
{ type: 'SOA',
nsname: 'ns1.example.com',
hostmaster: 'admin.example.com',
serial: 156696742,
refresh: 900,
retry: 900,
expire: 1800,
minttl: 60 } ]
域名系统服务器服务商可以选择不响应 ANY
查询。调用单个方法(如 dns.resolve4()
、dns.resolveMx()
等)可能会更好。更多详细信息,请参见 RFC 8482。
¥DNS server operators may choose not to respond to ANY
queries. It may be better to call individual methods like dns.resolve4()
,
dns.resolveMx()
, and so on. For more details, see RFC 8482.
dns.resolveCname(hostname, callback)
#
-
hostname
<string> -
callback
<Function>-
err
<Error> -
addresses
<string[]>
-
使用域名系统协议为 hostname
解析 CNAME
记录。传给 callback
函数的 addresses
参数将包含可用于 hostname
(例如 ['bar.example.com']
)的规范名称记录的数组。
¥Uses the DNS protocol to resolve CNAME
records for the hostname
. The
addresses
argument passed to the callback
function
will contain an array of canonical name records available for the hostname
(e.g. ['bar.example.com']
).
dns.resolveCaa(hostname, callback)
#
-
hostname
<string> -
callback
<Function>-
err
<Error> -
records
<Object[]>
-
使用域名系统协议为 hostname
解析 CAA
记录。传给 callback
函数的 addresses
参数将包含可用于 hostname
(例如 [{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]
)的证书颁发机构授权记录的数组。
¥Uses the DNS protocol to resolve CAA
records for the hostname
. The
addresses
argument passed to the callback
function
will contain an array of certification authority authorization records
available for the hostname
(e.g. [{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]
).
dns.resolveMx(hostname, callback)
#
-
hostname
<string> -
callback
<Function>-
err
<Error> -
addresses
<Object[]>
-
使用域名系统协议解析 hostname
的邮件交换记录(MX
记录)。传给 callback
函数的 addresses
参数将包含其中包含 priority
和 exchange
属性(例如 [{priority: 10, exchange: 'mx.example.com'}, ...]
)的对象数组。
¥Uses the DNS protocol to resolve mail exchange records (MX
records) for the
hostname
. The addresses
argument passed to the callback
function will
contain an array of objects containing both a priority
and exchange
property (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]
).
dns.resolveNaptr(hostname, callback)
#
-
hostname
<string> -
callback
<Function>-
err
<Error> -
addresses
<Object[]>
-
使用域名系统协议为 hostname
解析基于正则表达式的记录(NAPTR
记录)。传给 callback
函数的 addresses
参数将包含具有以下属性的对象数组:
¥Uses the DNS protocol to resolve regular expression-based records (NAPTR
records) for the hostname
. The addresses
argument passed to the callback
function will contain an array of objects with the following properties:
-
flags
-
service
-
regexp
-
replacement
-
order
-
preference
{
flags: 's',
service: 'SIP+D2U',
regexp: '',
replacement: '_sip._udp.example.com',
order: 30,
preference: 100
}
dns.resolveNs(hostname, callback)
#
-
hostname
<string> -
callback
<Function>-
err
<Error> -
addresses
<string[]>
-
使用域名系统协议为 hostname
解析名称服务器记录(NS
记录)。传给 callback
函数的 addresses
参数将包含可用于 hostname
(例如 ['ns1.example.com', 'ns2.example.com']
)的名称服务器记录数组。
¥Uses the DNS protocol to resolve name server records (NS
records) for the
hostname
. The addresses
argument passed to the callback
function will
contain an array of name server records available for hostname
(e.g. ['ns1.example.com', 'ns2.example.com']
).
dns.resolvePtr(hostname, callback)
#
-
hostname
<string> -
callback
<Function>-
err
<Error> -
addresses
<string[]>
-
使用域名系统协议解析 hostname
的指针记录(PTR
记录)。传给 callback
函数的 addresses
参数将是包含响应记录的字符串数组。
¥Uses the DNS protocol to resolve pointer records (PTR
records) for the
hostname
. The addresses
argument passed to the callback
function will
be an array of strings containing the reply records.
dns.resolveSoa(hostname, callback)
#
-
hostname
<string> -
callback
<Function>
使用域名系统协议来解析 hostname
的起始规范记录(SOA
记录)。传给 callback
函数的 address
参数将是具有以下属性的对象:
¥Uses the DNS protocol to resolve a start of authority record (SOA
record) for
the hostname
. The address
argument passed to the callback
function will
be an object with the following properties:
-
nsname
-
hostmaster
-
serial
-
refresh
-
retry
-
expire
-
minttl
{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
dns.resolveSrv(hostname, callback)
#
-
hostname
<string> -
callback
<Function>-
err
<Error> -
addresses
<Object[]>
-
使用域名系统协议解析 hostname
的服务记录(SRV
记录)。传给 callback
函数的 addresses
参数将是具有以下属性的对象数组:
¥Uses the DNS protocol to resolve service records (SRV
records) for the
hostname
. The addresses
argument passed to the callback
function will
be an array of objects with the following properties:
-
priority
-
weight
-
port
-
name
{
priority: 10,
weight: 5,
port: 21223,
name: 'service.example.com'
}
dns.resolveTxt(hostname, callback)
#
-
hostname
<string> -
callback
<Function>-
err
<Error> -
records
<string[][]>
-
使用域名系统协议为 hostname
解析文本查询(TXT
记录)。传给 callback
函数的 records
参数是可用于 hostname
(例如 [ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]
)的文本记录的二维数组。每个子数组包含一条记录的 TXT 块。根据用例,这些可以连接在一起或单独处理。
¥Uses the DNS protocol to resolve text queries (TXT
records) for the
hostname
. The records
argument passed to the callback
function is a
two-dimensional array of the text records available for hostname
(e.g.
[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]
). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.
dns.reverse(ip, callback)
#
-
ip
<string> -
callback
<Function>-
err
<Error> -
hostnames
<string[]>
-
执行反向域名系统查询,将 IPv4 或 IPv6 地址解析为主机名数组。
¥Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names.
出错时,err
是一个 Error
对象,其中 err.code
是 DNS 错误代码 之一。
¥On error, err
is an Error
object, where err.code
is
one of the DNS error codes.
dns.setDefaultResultOrder(order)
#
-
order
<string> 必须是'ipv4first'
、'ipv6first'
或'verbatim'
。¥
order
<string> must be'ipv4first'
,'ipv6first'
or'verbatim'
.
在 dns.lookup()
和 dnsPromises.lookup()
中设置 order
的默认值。该值可能是:
¥Set the default value of order
in dns.lookup()
and
dnsPromises.lookup()
. The value could be:
-
ipv4first
:将默认order
设置为ipv4first
。¥
ipv4first
: sets defaultorder
toipv4first
. -
ipv6first
:将默认order
设置为ipv6first
。¥
ipv6first
: sets defaultorder
toipv6first
. -
verbatim
:将默认order
设置为verbatim
。¥
verbatim
: sets defaultorder
toverbatim
.
默认为 verbatim
,并且 dns.setDefaultResultOrder()
的优先级高于 --dns-result-order
。当使用 工作线程 时,主线程中的 dns.setDefaultResultOrder()
不会影响 worker 中的默认 dns 命令。
¥The default is verbatim
and dns.setDefaultResultOrder()
have higher
priority than --dns-result-order
. When using worker threads,
dns.setDefaultResultOrder()
from the main thread won't affect the default
dns orders in workers.
dns.getDefaultResultOrder()
#
在 dns.lookup()
和 dnsPromises.lookup()
中获取 order
的默认值。该值可能是:
¥Get the default value for order
in dns.lookup()
and
dnsPromises.lookup()
. The value could be:
-
ipv4first
:对于order
默认为ipv4first
。¥
ipv4first
: fororder
defaulting toipv4first
. -
ipv6first
:对于order
默认为ipv6first
。¥
ipv6first
: fororder
defaulting toipv6first
. -
verbatim
:对于order
默认为verbatim
。¥
verbatim
: fororder
defaulting toverbatim
.
dns.setServers(servers)
#
-
servers
<string[]> RFC 5952 格式的地址数组¥
servers
<string[]> array of RFC 5952 formatted addresses
设置执行 DNS 解析时要使用的服务器的 IP 地址和端口。servers
参数是 RFC 5952 格式地址的数组。如果端口是 IANA 默认 DNS 端口 (53),则可以省略。
¥Sets the IP address and port of servers to be used when performing DNS
resolution. The servers
argument is an array of RFC 5952 formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.
dns.setServers([
'8.8.8.8',
'[2001:4860:4860::8888]',
'8.8.8.8:1053',
'[2001:4860:4860::8888]:1053',
]);
如果提供的地址无效,则会抛出错误。
¥An error will be thrown if an invalid address is provided.
在进行域名系统查询时不得调用 dns.setServers()
方法。
¥The dns.setServers()
method must not be called while a DNS query is in
progress.
dns.setServers()
方法仅影响 dns.resolve()
、dns.resolve*()
和 dns.reverse()
(特别是不影响 dns.lookup()
)。
¥The dns.setServers()
method affects only dns.resolve()
,
dns.resolve*()
and dns.reverse()
(and specifically not
dns.lookup()
).
此方法的工作原理与 resolve.conf 非常相似。也就是说,如果尝试使用提供的第一个服务器进行解析导致 NOTFOUND
错误,则 resolve()
方法将不会尝试使用提供的后续服务器进行解析。仅当较早的域名系统服务器超时或导致其他错误时,才会使用后备域名系统服务器。
¥This method works much like
resolve.conf.
That is, if attempting to resolve with the first server provided results in a
NOTFOUND
error, the resolve()
method will not attempt to resolve with
subsequent servers provided. Fallback DNS servers will only be used if the
earlier ones time out or result in some other error.
DNS promise API#
dns.promises
API 提供了一组替代的异步 DNS 方法,这些方法返回 Promise
对象而不是使用回调。API 可通过 require('node:dns').promises
或 require('node:dns/promises')
访问。
¥The dns.promises
API provides an alternative set of asynchronous DNS methods
that return Promise
objects rather than using callbacks. The API is accessible
via require('node:dns').promises
or require('node:dns/promises')
.
类:dnsPromises.Resolver
#
¥Class: dnsPromises.Resolver
域名系统请求的独立解析器。
¥An independent resolver for DNS requests.
创建新的解析器使用默认的服务器设置。使用 resolver.setServers()
设置用于解析器的服务器不会影响其他解析器:
¥Creating a new resolver uses the default server settings. Setting
the servers used for a resolver using
resolver.setServers()
does not affect
other resolvers:
import { Resolver } from 'node:dns/promises';
const resolver = new Resolver();
resolver.setServers(['4.4.4.4']);
// This request will use the server at 4.4.4.4, independent of global settings.
const addresses = await resolver.resolve4('example.org');
const { Resolver } = require('node:dns').promises;
const resolver = new Resolver();
resolver.setServers(['4.4.4.4']);
// This request will use the server at 4.4.4.4, independent of global settings.
resolver.resolve4('example.org').then((addresses) => {
// ...
});
// Alternatively, the same code can be written using async-await style.
(async function() {
const addresses = await resolver.resolve4('example.org');
})();
来自 dnsPromises
API 的以下方法可用:
¥The following methods from the dnsPromises
API are available:
resolver.cancel()
#
取消此解析器进行的所有未完成的域名系统查询。相应的 promise 将使用错误码 ECANCELLED
拒绝。
¥Cancel all outstanding DNS queries made by this resolver. The corresponding
promises will be rejected with an error with the code ECANCELLED
.
dnsPromises.getServers()
#
-
返回:<string[]>
¥Returns: <string[]>
返回 IP 地址字符串数组,格式根据 RFC 5952,当前配置为 DNS 解析。如果使用自定义端口,则字符串将包含端口部分。
¥Returns an array of IP address strings, formatted according to RFC 5952, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.
[
'8.8.8.8',
'2001:4860:4860::8888',
'8.8.8.8:1053',
'[2001:4860:4860::8888]:1053',
]
dnsPromises.lookup(hostname[, options])
#
-
hostname
<string> -
-
family
<integer> 记录族。必须是4
、6
或0
。值0
指示返回 IPv4 或 IPv6 地址。如果值0
与{ all: true }
一起使用(见下文),则返回 IPv4 和 IPv6 地址之一或两者,具体取决于系统的 DNS 解析器。默认值:0
。¥
family
<integer> The record family. Must be4
,6
, or0
. The value0
indicates that either an IPv4 or IPv6 address is returned. If the value0
is used with{ all: true }
(see below), either one of or both IPv4 and IPv6 addresses are returned, depending on the system's DNS resolver. Default:0
. -
hints
<number> 一个或多个 支持的getaddrinfo
标志。多个标志可以通过按位OR
其值来传入。¥
hints
<number> One or more supportedgetaddrinfo
flags. Multiple flags may be passed by bitwiseOR
ing their values. -
all
<boolean> 当为true
时,Promise
使用数组中的所有地址进行解决。否则,返回单个地址。默认值:false
。¥
all
<boolean> Whentrue
, thePromise
is resolved with all addresses in an array. Otherwise, returns a single address. Default:false
. -
order
<string> 当为verbatim
时,Promise
使用按照 DNS 解析器返回的顺序使用 IPv4 和 IPv6 地址进行解决。当为ipv4first
时,IPv4 地址位于 IPv6 地址之前。当ipv6first
时,IPv6 地址位于 IPv4 地址之前。默认值:verbatim
(地址未重新排序)。默认值可使用dns.setDefaultResultOrder()
或--dns-result-order
进行配置。新代码应使用{ order: 'verbatim' }
。¥
order
<string> Whenverbatim
, thePromise
is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. Whenipv4first
, IPv4 addresses are placed before IPv6 addresses. Whenipv6first
, IPv6 addresses are placed before IPv4 addresses. Default:verbatim
(addresses are not reordered). Default value is configurable usingdns.setDefaultResultOrder()
or--dns-result-order
. New code should use{ order: 'verbatim' }
. -
verbatim
<boolean> 当为true
时,Promise
使用按照 DNS 解析器返回的顺序使用 IPv4 和 IPv6 地址进行解决。当为false
时,IPv4 地址位于 IPv6 地址之前。此选项将被弃用,取而代之的是order
。当两者都指定时,order
具有更高的优先级。新代码应仅使用order
。默认值:目前是false
(地址已重新排序),但预计在不久的将来会发生变化。默认值可使用dns.setDefaultResultOrder()
或--dns-result-order
进行配置。¥
verbatim
<boolean> Whentrue
, thePromise
is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. Whenfalse
, IPv4 addresses are placed before IPv6 addresses. This option will be deprecated in favor oforder
. When both are specified,order
has higher precedence. New code should only useorder
. Default: currentlyfalse
(addresses are reordered) but this is expected to change in the not too distant future. Default value is configurable usingdns.setDefaultResultOrder()
or--dns-result-order
.
-
将主机名(例如 'nodejs.org'
)解析为第一个找到的 A (IPv4) 或 AAAA (IPv6) 记录。所有 option
属性都是可选的。如果 options
是整数,则它必须是 4
或 6
– 如果未提供 options
,则返回 IPv4 或 IPv6 地址,或两者(如果找到)。
¥Resolves a host name (e.g. 'nodejs.org'
) into the first found A (IPv4) or
AAAA (IPv6) record. All option
properties are optional. If options
is an
integer, then it must be 4
or 6
– if options
is not provided, then
either IPv4 or IPv6 addresses, or both, are returned if found.
将 all
选项设置为 true
,则 Promise
使用 addresses
是具有属性 address
和 family
的对象数组进行解决。
¥With the all
option set to true
, the Promise
is resolved with addresses
being an array of objects with the properties address
and family
.
当出错时,Promise
使用 Error
对象拒绝,其中 err.code
是错误码。记住,err.code
将设置为 'ENOTFOUND'
,不仅当主机名不存在时,而且当查找以其他方式失败时,例如没有可用的文件描述符。
¥On error, the Promise
is rejected with an Error
object, where err.code
is the error code.
Keep in mind that err.code
will be set to 'ENOTFOUND'
not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.
dnsPromises.lookup()
不一定与域名系统协议有任何关系。该实现使用一种操作系统工具,可以将名称与地址关联起来,反之亦然。这种实现会对任何 Node.js 程序的行为产生微妙但重要的影响。在使用 dnsPromises.lookup()
之前,请花一些时间查阅 实现的注意事项章节。
¥dnsPromises.lookup()
does not necessarily have anything to do with the DNS
protocol. The implementation uses an operating system facility that can
associate names with addresses and vice versa. This implementation can have
subtle but important consequences on the behavior of any Node.js program. Please
take some time to consult the Implementation considerations section before
using dnsPromises.lookup()
.
用法示例:
¥Example usage:
import dns from 'node:dns';
const dnsPromises = dns.promises;
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
await dnsPromises.lookup('example.org', options).then((result) => {
console.log('address: %j family: IPv%s', result.address, result.family);
// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6
});
// When options.all is true, the result will be an Array.
options.all = true;
await dnsPromises.lookup('example.org', options).then((result) => {
console.log('addresses: %j', result);
// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]
});
const dns = require('node:dns');
const dnsPromises = dns.promises;
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dnsPromises.lookup('example.org', options).then((result) => {
console.log('address: %j family: IPv%s', result.address, result.family);
// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6
});
// When options.all is true, the result will be an Array.
options.all = true;
dnsPromises.lookup('example.org', options).then((result) => {
console.log('addresses: %j', result);
// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]
});
dnsPromises.lookupService(address, port)
#
使用操作系统的底层 getnameinfo
实现将给定的 address
和 port
解析为主机名和服务。
¥Resolves the given address
and port
into a host name and service using
the operating system's underlying getnameinfo
implementation.
如果 address
不是有效的 IP 地址,则会抛出 TypeError
。port
将被强制为数字。如果不是合法的端口,则会抛出 TypeError
。
¥If address
is not a valid IP address, a TypeError
will be thrown.
The port
will be coerced to a number. If it is not a legal port, a TypeError
will be thrown.
当出错时,Promise
使用 Error
对象拒绝,其中 err.code
是错误码。
¥On error, the Promise
is rejected with an Error
object, where err.code
is the error code.
import dnsPromises from 'node:dns/promises';
const result = await dnsPromises.lookupService('127.0.0.1', 22);
console.log(result.hostname, result.service); // Prints: localhost ssh
const dnsPromises = require('node:dns').promises;
dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
console.log(result.hostname, result.service);
// Prints: localhost ssh
});
dnsPromises.resolve(hostname[, rrtype])
#
-
hostname
<string> 要解析的主机名。¥
hostname
<string> Host name to resolve. -
rrtype
<string> 资源记录类型。默认值:'A'
。¥
rrtype
<string> Resource record type. Default:'A'
.
使用域名系统协议将主机名(例如 'nodejs.org'
)解析为资源记录数组。当成功时,Promise
使用资源记录数组解决。个别结果的类型和结构因 rrtype
而异:
¥Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org'
) into an array
of the resource records. When successful, the Promise
is resolved with an
array of resource records. The type and structure of individual results vary
based on rrtype
:
rrtype | records 包含 | 结果类型 | 速记法 |
---|---|---|---|
'A' | IPv4 地址(默认) | <string> | dnsPromises.resolve4() |
'AAAA' | IPv6 地址 | <string> | dnsPromises.resolve6() |
'ANY' | 任何记录 | <Object> | dnsPromises.resolveAny() |
'CAA' | CA 授权记录 | <Object> | dnsPromises.resolveCaa() |
'CNAME' | 规范名称记录 | <string> | dnsPromises.resolveCname() |
'MX' | 邮件交换记录 | <Object> | dnsPromises.resolveMx() |
'NAPTR' | 名称权限指针记录 | <Object> | dnsPromises.resolveNaptr() |
'NS' | 名称服务器记录 | <string> | dnsPromises.resolveNs() |
'PTR' | 指针记录 | <string> | dnsPromises.resolvePtr() |
'SOA' | 权限记录的开始 | <Object> | dnsPromises.resolveSoa() |
'SRV' | 服务记录 | <Object> | dnsPromises.resolveSrv() |
'TXT' | 文本记录 | <string[]> | dnsPromises.resolveTxt() |
出错时,Promise
被 Error
对象拒绝,其中 err.code
是 DNS 错误代码 之一。
¥On error, the Promise
is rejected with an Error
object, where err.code
is one of the DNS error codes.
dnsPromises.resolve4(hostname[, options])
#
-
hostname
<string> 要解析的主机名。¥
hostname
<string> Host name to resolve. -
options
<Object>-
ttl
<boolean> 检索每条记录的生存时间值 (TTL)。当为true
时,Promise
使用{ address: '1.2.3.4', ttl: 60 }
对象数组而不是字符串数组进行解决,TTL 以秒表示。¥
ttl
<boolean> Retrieve the Time-To-Live value (TTL) of each record. Whentrue
, thePromise
is resolved with an array of{ address: '1.2.3.4', ttl: 60 }
objects rather than an array of strings, with the TTL expressed in seconds.
-
使用域名系统协议为 hostname
解析 IPv4 地址(A
记录)。当成功时,Promise
使用 IPv4 地址数值(例如 ['74.125.79.104', '74.125.79.105', '74.125.79.106']
)解决。
¥Uses the DNS protocol to resolve IPv4 addresses (A
records) for the
hostname
. On success, the Promise
is resolved with an array of IPv4
addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']
).
dnsPromises.resolve6(hostname[, options])
#
-
hostname
<string> 要解析的主机名。¥
hostname
<string> Host name to resolve. -
options
<Object>-
ttl
<boolean> 检索每条记录的生存时间值 (TTL)。当为true
时,Promise
使用{ address: '0:1:2:3:4:5:6:7', ttl: 60 }
对象数组而不是字符串数组进行解决,TTL 以秒表示。¥
ttl
<boolean> Retrieve the Time-To-Live value (TTL) of each record. Whentrue
, thePromise
is resolved with an array of{ address: '0:1:2:3:4:5:6:7', ttl: 60 }
objects rather than an array of strings, with the TTL expressed in seconds.
-
使用域名系统协议为 hostname
解析 IPv6 地址(AAAA
记录)。当成功时,Promise
使用 IPv6 地址数组解决。
¥Uses the DNS protocol to resolve IPv6 addresses (AAAA
records) for the
hostname
. On success, the Promise
is resolved with an array of IPv6
addresses.
dnsPromises.resolveAny(hostname)
#
hostname
<string>
使用域名系统协议解析所有记录(也称为 ANY
或 *
查询)。当成功时,Promise
使用包含各种类型记录的数组进行解决。每个对象都有表示当前记录的类型的属性 type
。并且根据 type
,对象上将出现其他属性:
¥Uses the DNS protocol to resolve all records (also known as ANY
or *
query).
On success, the Promise
is resolved with an array containing various types of
records. Each object has a property type
that indicates the type of the
current record. And depending on the type
, additional properties will be
present on the object:
类型 | 属性 |
---|---|
'A' | address /ttl |
'AAAA' | address /ttl |
'CNAME' | value |
'MX' | 参考 dnsPromises.resolveMx() |
'NAPTR' | 参考 dnsPromises.resolveNaptr() |
'NS' | value |
'PTR' | value |
'SOA' | 参考 dnsPromises.resolveSoa() |
'SRV' | 参考 dnsPromises.resolveSrv() |
'TXT' | 这种类型的记录包含一个名为 entries 的数组属性,它引用 dnsPromises.resolveTxt() ,例如 { entries: ['...'], type: 'TXT' } |
以下是结果对象的示例:
¥Here is an example of the result object:
[ { type: 'A', address: '127.0.0.1', ttl: 299 },
{ type: 'CNAME', value: 'example.com' },
{ type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
{ type: 'NS', value: 'ns1.example.com' },
{ type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
{ type: 'SOA',
nsname: 'ns1.example.com',
hostmaster: 'admin.example.com',
serial: 156696742,
refresh: 900,
retry: 900,
expire: 1800,
minttl: 60 } ]
dnsPromises.resolveCaa(hostname)
#
hostname
<string>
使用域名系统协议为 hostname
解析 CAA
记录。当成功时,Promise
使用包含可用于 hostname
(例如 [{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]
)的可用证书颁发机构授权记录的对象数组进行解决。
¥Uses the DNS protocol to resolve CAA
records for the hostname
. On success,
the Promise
is resolved with an array of objects containing available
certification authority authorization records available for the hostname
(e.g. [{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]
).
dnsPromises.resolveCname(hostname)
#
hostname
<string>
使用域名系统协议为 hostname
解析 CNAME
记录。当成功时,Promise
使用 hostname
可用的规范名称记录数组(例如 ['bar.example.com']
)进行解决。
¥Uses the DNS protocol to resolve CNAME
records for the hostname
. On success,
the Promise
is resolved with an array of canonical name records available for
the hostname
(e.g. ['bar.example.com']
).
dnsPromises.resolveMx(hostname)
#
hostname
<string>
使用域名系统协议解析 hostname
的邮件交换记录(MX
记录)。当成功时,Promise
使用包含 priority
和 exchange
属性(例如 [{priority: 10, exchange: 'mx.example.com'}, ...]
)的对象数组进行解决。
¥Uses the DNS protocol to resolve mail exchange records (MX
records) for the
hostname
. On success, the Promise
is resolved with an array of objects
containing both a priority
and exchange
property (e.g.
[{priority: 10, exchange: 'mx.example.com'}, ...]
).
dnsPromises.resolveNaptr(hostname)
#
hostname
<string>
使用域名系统协议为 hostname
解析基于正则表达式的记录(NAPTR
记录)。当成功时,Promise
使用具有以下属性的对象数组进行解决:
¥Uses the DNS protocol to resolve regular expression-based records (NAPTR
records) for the hostname
. On success, the Promise
is resolved with an array
of objects with the following properties:
-
flags
-
service
-
regexp
-
replacement
-
order
-
preference
{
flags: 's',
service: 'SIP+D2U',
regexp: '',
replacement: '_sip._udp.example.com',
order: 30,
preference: 100
}
dnsPromises.resolveNs(hostname)
#
hostname
<string>
使用域名系统协议为 hostname
解析名称服务器记录(NS
记录)。当成功时,Promise
使用可用于 hostname
的名称服务器记录数组(例如 ['ns1.example.com', 'ns2.example.com']
)进行解决。
¥Uses the DNS protocol to resolve name server records (NS
records) for the
hostname
. On success, the Promise
is resolved with an array of name server
records available for hostname
(e.g.
['ns1.example.com', 'ns2.example.com']
).
dnsPromises.resolvePtr(hostname)
#
hostname
<string>
使用域名系统协议解析 hostname
的指针记录(PTR
记录)。当成功时,Promise
使用包含响应记录的字符串数组进行解决。
¥Uses the DNS protocol to resolve pointer records (PTR
records) for the
hostname
. On success, the Promise
is resolved with an array of strings
containing the reply records.
dnsPromises.resolveSoa(hostname)
#
hostname
<string>
使用域名系统协议来解析 hostname
的起始规范记录(SOA
记录)。当成功时,Promise
使用具有以下属性的对象进行解决:
¥Uses the DNS protocol to resolve a start of authority record (SOA
record) for
the hostname
. On success, the Promise
is resolved with an object with the
following properties:
-
nsname
-
hostmaster
-
serial
-
refresh
-
retry
-
expire
-
minttl
{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
dnsPromises.resolveSrv(hostname)
#
hostname
<string>
使用域名系统协议解析 hostname
的服务记录(SRV
记录)。当成功时,Promise
使用具有以下属性的对象数组进行解决:
¥Uses the DNS protocol to resolve service records (SRV
records) for the
hostname
. On success, the Promise
is resolved with an array of objects with
the following properties:
-
priority
-
weight
-
port
-
name
{
priority: 10,
weight: 5,
port: 21223,
name: 'service.example.com'
}
dnsPromises.resolveTxt(hostname)
#
hostname
<string>
使用域名系统协议为 hostname
解析文本查询(TXT
记录)。当成功时,Promise
使用可用于 hostname
(例如 [ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]
)的文本记录的二维数组进行解决。每个子数组包含一条记录的 TXT 块。根据用例,这些可以连接在一起或单独处理。
¥Uses the DNS protocol to resolve text queries (TXT
records) for the
hostname
. On success, the Promise
is resolved with a two-dimensional array
of the text records available for hostname
(e.g.
[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]
). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.
dnsPromises.reverse(ip)
#
ip
<string>
执行反向域名系统查询,将 IPv4 或 IPv6 地址解析为主机名数组。
¥Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names.
出错时,Promise
被 Error
对象拒绝,其中 err.code
是 DNS 错误代码 之一。
¥On error, the Promise
is rejected with an Error
object, where err.code
is one of the DNS error codes.
dnsPromises.setDefaultResultOrder(order)
#
-
order
<string> 必须是'ipv4first'
、'ipv6first'
或'verbatim'
。¥
order
<string> must be'ipv4first'
,'ipv6first'
or'verbatim'
.
在 dns.lookup()
和 dnsPromises.lookup()
中设置 order
的默认值。该值可能是:
¥Set the default value of order
in dns.lookup()
and
dnsPromises.lookup()
. The value could be:
-
ipv4first
:将默认order
设置为ipv4first
。¥
ipv4first
: sets defaultorder
toipv4first
. -
ipv6first
:将默认order
设置为ipv6first
。¥
ipv6first
: sets defaultorder
toipv6first
. -
verbatim
:将默认order
设置为verbatim
。¥
verbatim
: sets defaultorder
toverbatim
.
默认为 verbatim
,并且 dnsPromises.setDefaultResultOrder()
的优先级高于 --dns-result-order
。当使用 工作线程 时,主线程中的 dnsPromises.setDefaultResultOrder()
不会影响 worker 中的默认 dns 命令。
¥The default is verbatim
and dnsPromises.setDefaultResultOrder()
have
higher priority than --dns-result-order
. When using worker threads,
dnsPromises.setDefaultResultOrder()
from the main thread won't affect the
default dns orders in workers.
dnsPromises.getDefaultResultOrder()
#
获取 dnsOrder
的值。
¥Get the value of dnsOrder
.
dnsPromises.setServers(servers)
#
-
servers
<string[]> RFC 5952 格式的地址数组¥
servers
<string[]> array of RFC 5952 formatted addresses
设置执行 DNS 解析时要使用的服务器的 IP 地址和端口。servers
参数是 RFC 5952 格式地址的数组。如果端口是 IANA 默认 DNS 端口 (53),则可以省略。
¥Sets the IP address and port of servers to be used when performing DNS
resolution. The servers
argument is an array of RFC 5952 formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.
dnsPromises.setServers([
'8.8.8.8',
'[2001:4860:4860::8888]',
'8.8.8.8:1053',
'[2001:4860:4860::8888]:1053',
]);
如果提供的地址无效,则会抛出错误。
¥An error will be thrown if an invalid address is provided.
在进行域名系统查询时不得调用 dnsPromises.setServers()
方法。
¥The dnsPromises.setServers()
method must not be called while a DNS query is in
progress.
此方法的工作原理与 resolve.conf 非常相似。也就是说,如果尝试使用提供的第一个服务器进行解析导致 NOTFOUND
错误,则 resolve()
方法将不会尝试使用提供的后续服务器进行解析。仅当较早的域名系统服务器超时或导致其他错误时,才会使用后备域名系统服务器。
¥This method works much like
resolve.conf.
That is, if attempting to resolve with the first server provided results in a
NOTFOUND
error, the resolve()
method will not attempt to resolve with
subsequent servers provided. Fallback DNS servers will only be used if the
earlier ones time out or result in some other error.
错误代码#
¥Error codes
每个域名系统查询都可以返回以下错误代码之一:
¥Each DNS query can return one of the following error codes:
-
dns.NODATA
:域名系统服务器返回没有数据的答案。¥
dns.NODATA
: DNS server returned an answer with no data. -
dns.FORMERR
:域名系统服务器声称查询格式错误。¥
dns.FORMERR
: DNS server claims query was misformatted. -
dns.SERVFAIL
:域名系统服务器返回一般故障。¥
dns.SERVFAIL
: DNS server returned general failure. -
dns.NOTFOUND
:未找到域名。¥
dns.NOTFOUND
: Domain name not found. -
dns.NOTIMP
:域名系统服务器没有执行请求的操作。¥
dns.NOTIMP
: DNS server does not implement the requested operation. -
dns.REFUSED
:域名系统服务器拒绝查询。¥
dns.REFUSED
: DNS server refused query. -
dns.BADQUERY
:域名系统查询格式错误。¥
dns.BADQUERY
: Misformatted DNS query. -
dns.BADNAME
:主机名格式错误。¥
dns.BADNAME
: Misformatted host name. -
dns.BADFAMILY
:不支持的地址族。¥
dns.BADFAMILY
: Unsupported address family. -
dns.BADRESP
:DNS 响应格式错误。¥
dns.BADRESP
: Misformatted DNS reply. -
dns.CONNREFUSED
:无法联系域名系统服务器。¥
dns.CONNREFUSED
: Could not contact DNS servers. -
dns.TIMEOUT
:联系域名系统服务器时超时。¥
dns.TIMEOUT
: Timeout while contacting DNS servers. -
dns.EOF
:文件结束。¥
dns.EOF
: End of file. -
dns.FILE
:读取文件时出错。¥
dns.FILE
: Error reading file. -
dns.NOMEM
:内存不足。¥
dns.NOMEM
: Out of memory. -
dns.DESTRUCTION
:渠道正在被销毁。¥
dns.DESTRUCTION
: Channel is being destroyed. -
dns.BADSTR
:格式错误的字符串。¥
dns.BADSTR
: Misformatted string. -
dns.BADFLAGS
:指定了非法标志。¥
dns.BADFLAGS
: Illegal flags specified. -
dns.NONAME
:给定的主机名不是数字。¥
dns.NONAME
: Given host name is not numeric. -
dns.BADHINTS
:指定了非法提示标志。¥
dns.BADHINTS
: Illegal hints flags specified. -
dns.NOTINITIALIZED
:c-ares 库初始化尚未执行。¥
dns.NOTINITIALIZED
: c-ares library initialization not yet performed. -
dns.LOADIPHLPAPI
:加载iphlpapi.dll
时出错。¥
dns.LOADIPHLPAPI
: Error loadingiphlpapi.dll
. -
dns.ADDRGETNETWORKPARAMS
:找不到GetNetworkParams
函数。¥
dns.ADDRGETNETWORKPARAMS
: Could not findGetNetworkParams
function. -
dns.CANCELLED
:域名系统查询已取消。¥
dns.CANCELLED
: DNS query cancelled.
dnsPromises
API 也导出上述错误代码,例如,dnsPromises.NODATA
。
¥The dnsPromises
API also exports the above error codes, e.g., dnsPromises.NODATA
.
实现的注意事项#
¥Implementation considerations
尽管 dns.lookup()
和各种 dns.resolve*()/dns.reverse()
函数具有将网络名称与网络地址相关联的相同目标(反之亦然),但它们的行为却大不相同。这些差异可能会对 Node.js 程序的行为产生微妙但重要的影响。
¥Although dns.lookup()
and the various dns.resolve*()/dns.reverse()
functions have the same goal of associating a network name with a network
address (or vice versa), their behavior is quite different. These differences
can have subtle but significant consequences on the behavior of Node.js
programs.
dns.lookup()
#
在幕后,dns.lookup()
使用与大多数其他程序相同的操作系统设施。例如,dns.lookup()
几乎总是以与 ping
命令相同的方式解析给定名称。在大多数类似 POSIX 的操作系统上,可以通过更改 nsswitch.conf(5)
和/或 resolv.conf(5)
中的设置来修改 dns.lookup()
函数的行为,但更改这些文件将更改正在运行的所有其他程序的行为 在同一操作系统上。
¥Under the hood, dns.lookup()
uses the same operating system facilities
as most other programs. For instance, dns.lookup()
will almost always
resolve a given name the same way as the ping
command. On most POSIX-like
operating systems, the behavior of the dns.lookup()
function can be
modified by changing settings in nsswitch.conf(5)
and/or resolv.conf(5)
,
but changing these files will change the behavior of all other
programs running on the same operating system.
尽管从 JavaScript 的角度来看,对 dns.lookup()
的调用是异步的,但它是作为对在 libuv 线程池上运行的 getaddrinfo(3)
的同步调用来实现的。这可能会对某些应用产生令人惊讶的负面性能影响,有关更多信息,请参阅 UV_THREADPOOL_SIZE
文档。
¥Though the call to dns.lookup()
will be asynchronous from JavaScript's
perspective, it is implemented as a synchronous call to getaddrinfo(3)
that runs
on libuv's threadpool. This can have surprising negative performance
implications for some applications, see the UV_THREADPOOL_SIZE
documentation for more information.
各种网络 API 将在内部调用 dns.lookup()
来解析主机名。如果这是一个问题,则考虑使用 dns.resolve()
并使用地址而不是主机名将主机名解析为地址。此外,某些网络 API(例如 socket.connect()
和 dgram.createSocket()
)允许替换默认解析器 dns.lookup()
。
¥Various networking APIs will call dns.lookup()
internally to resolve
host names. If that is an issue, consider resolving the host name to an address
using dns.resolve()
and using the address instead of a host name. Also, some
networking APIs (such as socket.connect()
and dgram.createSocket()
)
allow the default resolver, dns.lookup()
, to be replaced.
dns.resolve()
、dns.resolve*()
和 dns.reverse()
#
¥dns.resolve()
, dns.resolve*()
, and dns.reverse()
这些函数的实现与 dns.lookup()
完全不同。它们不使用 getaddrinfo(3)
并且始终在网络上执行 DNS 查询。此网络通信始终异步完成,不使用 libuv 的线程池。
¥These functions are implemented quite differently than dns.lookup()
. They
do not use getaddrinfo(3)
and they always perform a DNS query on the
network. This network communication is always done asynchronously and does not
use libuv's threadpool.
因此,这些函数不会对发生在 libuv 线程池上的其他处理产生与 dns.lookup()
相同的负面影响。
¥As a result, these functions cannot have the same negative impact on other
processing that happens on libuv's threadpool that dns.lookup()
can have.
它们不使用 dns.lookup()
使用的同一组配置文件。例如,他们不使用来自 /etc/hosts
的配置。
¥They do not use the same set of configuration files that dns.lookup()
uses. For instance, they do not use the configuration from /etc/hosts
.