- assert - 断言
- Buffer - 缓冲器
- child_process - 子进程
- cluster - 集群
- console - 控制台
- crypto - 加密
- dgram - 数据报
- dns - 域名服务器
- Error - 异常
- events - 事件
- fs - 文件系统
- global - 全局变量
- http - HTTP
- https - HTTPS
- module - 模块
- net - 网络
- os - 操作系统
- path - 路径
- process - 进程
- querystring - 查询字符串
- readline - 逐行读取
- repl - 交互式解释器
- stream - 流
- string_decoder - 字符串解码器
- timer - 定时器
- tls - 安全传输层
- tty - 终端
- url - 网址
- util - 实用工具
- v8 - V8引擎
- vm - 虚拟机
- zlib - 压缩
Node.js v10.8.0 文档
目录
-
- dns.getServers()
- 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.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.setServers(servers)
-
- Class: dnsPromises.Resolver
- 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.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.setServers(servers)
- 错误码
dns (域名服务器)#
dns
模块包含两类函数:
1) 第一类函数,使用底层操作系统工具进行域名解析,且无需进行网络通信。
这类函数只有一个:dns.lookup()
。
例子,查找 iana.org
:
const dns = require('dns');
dns.lookup('iana.org', (err, address, family) => {
console.log('IP 地址: %j 地址族: IPv%s', address, family);
});
// IP 地址: "192.0.43.8" 地址族: IPv4
2) 第二类函数,连接到一个真实的 DNS 服务器进行域名解析,且始终使用网络进行 DNS 查询。
这类函数包含了 dns
模块中除 dns.lookup()
以外的所有函数。
这些函数使用与 dns.lookup()
不同的配置文件(例如 /etc/hosts
)。
这类函数适合于那些不想使用底层操作系统工具进行域名解析、而是想使用网络进行 DNS 查询的开发者。
例子,解析 'archive.org'
然后逆向解析返回的 IP 地址:
const dns = require('dns');
dns.resolve4('archive.org', (err, addresses) => {
if (err) throw err;
console.log(`IP 地址: ${JSON.stringify(addresses)}`);
addresses.forEach((a) => {
dns.reverse(a, (err, hostnames) => {
if (err) {
throw err;
}
console.log(`IP 地址 ${a} 逆向解析到域名: ${JSON.stringify(hostnames)}`);
});
});
});
两类函数有微妙的差别,详见 实现上的注意事项。
Class: dns.Resolver#
DNS请求的独立解析程序。
使用默认的设置创建一个新的解析程序。为一个解析程序设置servers使用resolver.setServers()
,它不会影响其他的解析程序:
const { Resolver } = require('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) => {
// ...
});
可以使用的dns
模块的方法如下:
resolver.getServers()
resolver.setServers()
resolver.resolve()
resolver.resolve4()
resolver.resolve6()
resolver.resolveAny()
resolver.resolveCname()
resolver.resolveMx()
resolver.resolveNaptr()
resolver.resolveNs()
resolver.resolvePtr()
resolver.resolveSoa()
resolver.resolveSrv()
resolver.resolveTxt()
resolver.reverse()
resolver.cancel()#
取消这个解析程序的未解决的DNS查询,相应的回调用一个ECANCELLED
码调用。
dns.getServers()#
返回一个用于当前DNS解析的IP地址的数组的字符串,格式根据rfc5952。如果使用自定义端口,那么字符串将包括一个端口部分。
例如:
[
'4.4.4.4',
'2001:4860:4860::8888',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053'
]
dns.lookup(hostname[, options], callback)#
hostname
<string>-
family
<integer> The record family. Must be4
or6
. IPv4 and IPv6 addresses are both returned by default.hints
<number> One or more supportedgetaddrinfo
flags. Multiple flags may be passed by bitwiseOR
ing their values.all
<boolean> Whentrue
, the callback returns all resolved addresses in an array. Otherwise, returns a single address. Default:false
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. Default: currentlyfalse
(addresses are reordered) but this is expected to change in the not too distant future. New code should use{ verbatim: true }
.
-
callback
<Function>
解析hostname
(例如:'nodejs.org'
)为第一个找到的A(IPv4)或AAAA(IPv6)记录。options
可以是对象或者整数。如果options
没有被提供,那么IPv4 和 IPv6都是有效的。如果options
是整数,只能是4
或6
。
另外,options
可以是一个含有以下属性的对象:
family
<number> - T地址族。如果提供,必须为整数4或6。如果没有提供,只接受IPv4和IPv6地址。hints
: <number> - 如果提供,它必须是一个或多个支持的getaddrinfo
标识。如果没有提供,那么没有标识被传递给getaddrinfo
。多个标识可以通过在逻辑上OR
ing它们的值,来传递给hints。支持的getaddrinfo
标识请参阅下文。有关支持的标志的更多信息请查询supportedgetaddrinfo
flags章节。all
: <boolean> - 值为true
时, 回调函数返回一个包含所有解析后地址的数组,否则只返回一个地址。默认值为false
。
所有的参数都是可选的。
回调函数包含(err, address, family)
参数。address
是IPv4或IPv6地址字符串。family
、是整数4或6,表示地址族(不一定是最初传递给查找的值)。
当all
属性被设置为true
时,回调函数参数变为(err, addresses)
,addresses
则变成一个由address
和 family
属性组成的对象数组。
发生错误时,err
是一个Error
对象,err.code
是错误码。不仅在主机名不存在时,在如没有可用的文件描述符等情况下查找失败,err.code也会被设置为'ENOENT'
。
dns.lookup()
不需要与DNS协议有任何关系。它仅仅是一个连接名字和地址的操作系统功能。在任何的node.js程序中,它的实现对表现有一些微妙但是重要的影响。在使用dns.lookup()
之前请花些时间查询Implementation considerations section章节。
使用例子:
const dns = require('dns');
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dns.lookup('example.com', options, (err, address, family) =>
console.log('address: %j family: IPv%s', address, family));
// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
// When options.all is true, the result will be an Array.
options.all = true;
dns.lookup('example.com', options, (err, addresses) =>
console.log('addresses: %j', addresses));
// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
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.
Supported getaddrinfo flags#
以下内容可以作为hints标志传递给dns.lookup()
。
dns.ADDRCONFIG
: 返回当前系统支持的地址类型。例如,如果当前系统至少配置了一个 IPv4 地址,则返回 IPv4地址。不考虑回环地址。dns.V4MAPPED
: 如果指定了 IPv6 家族, 但是没有找到 IPv6 地址,将返回 IPv4 映射的 IPv6地址。在有些操作系统中不支持(e.g FreeBSD 10.1)。
dns.lookupService(address, port, callback)#
address
<string>port
<number>-
callback
<Function>
将参数address
和port
传入操作系统底层getnameinfo
服务来解析处理并返回主机名。
如果address
不是有效的IP地址,会抛出TypeError
。port
必须是一个整数.如果不是规定的端口号,会抛出TypeError
.
出错情况下,err
是一个Error
对象,err.code
代码错误码。
const dns = require('dns');
dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
console.log(hostname, service);
// Prints: localhost ssh
});
如果以 util.promisify()
方式进行调用, 它将返回一个包含hostname
和service
属性的 Promise 对象。
dns.resolve(hostname[, rrtype], callback)#
hostname
<string> 解析的主机名。rrtype
<string> 资源记录类型. 默认:'A'
.-
callback
<Function>err
<Error>records
<string[]> | <Object[]> | <Object>
使用DNS协议来解析一个主机名(e.g. 'nodejs.org'
)为一个资源记录的数组。回调函数的参数为(err, records)
。当成功时,records
将是一个资源记录的数组。它的类型和结构取决于rrtype
:
rrtype | records contains | Result type | Shorthand method |
---|---|---|---|
'A' | IPv4 addresses (default) | <string> | dns.resolve4() |
'AAAA' | IPv6 addresses | <string> | dns.resolve6() |
'CNAME' | canonical name records | <string> | dns.resolveCname() |
'MX' | mail exchange records | <Object> | dns.resolveMx() |
'NAPTR' | name authority pointer records | <Object> | dns.resolveNaptr() |
'NS' | name server records | <string> | dns.resolveNs() |
'PTR' | pointer records | <string> | dns.resolvePtr() |
'SOA' | start of authority records | <Object> | dns.resolveSoa() |
'SRV' | service records | <Object> | dns.resolveSrv() |
'TXT' | text records | <string[]> | dns.resolveTxt() |
'ANY' | any records | <Object> | dns.resolveAny() |
出错时,err
是一个Error
object,err.code
是DNS error codes的一种。
dns.resolve4(hostname[, options], callback)#
hostname
<string> 需要解析的主机名。options
<Object> -ttl
<boolean> 记录每一条记录的存活次数 (TTL)。如果为true
, 返回的结果将会为Object
的数组,就像{ address: '1.2.3.4', ttl: 60 }
带有TTL
秒数的记录,而不是string
的数组.-
callback
<Function>err
<Error>addresses
<string[]> | <Object[]>
使用DNS
协议解析IPv4地址主机名(A
记录)。adresses
参数是传递给callback
函数的IPv4地址数组。(例如:['74.125.79.104', '74.125.79.105', '74.125.79.106']
)
dns.resolve6(hostname[, options], callback)#
hostname
<string> 需要解析的主机名。-
options
<Object>ttl
<boolean> 记录每一条记录的存活次数 (TTL)。如果为true
, 返回的结果将会为Object
的数组,就像{ address: '0:1:2:3:4:5:6:7', ttl: 60 }
带有TTL
秒数的记录,而不是string
的数组.
-
callback
<Function>err
<Error>addresses
<string[]> | <Object[]>
使用DNS
协议解析IPv6地址主机名(AAAA
记录)。adresses
参数是传递给callback
函数的IPv6地址数组.
dns.resolveAny(hostname, callback)#
hostname
<string>-
callback
<Function>err
<Error>ret
<Object[]>
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:
Type | Properties |
---|---|
'A' | address /ttl |
'AAAA' | address /ttl |
'CNAME' | value |
'MX' | Refer to dns.resolveMx() |
'NAPTR' | Refer to dns.resolveNaptr() |
'NS' | value |
'PTR' | value |
'SOA' | Refer to dns.resolveSoa() |
'SRV' | Refer to dns.resolveSrv() |
'TXT' | This type of record contains an array property called entries which refers to dns.resolveTxt() , e.g. { entries: ['...'], type: 'TXT' } |
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 } ]
dns.resolveCname(hostname, callback)#
hostname
<string>-
callback
<Function>err
<Error>addresses
<string[]>
使用DNS
协议解析CNAME
记录主机名。adresses
参数是传递给callback
函数规范内有效的主机名数组(例如:['bar.example.com']
).
dns.resolveMx(hostname, callback)#
hostname
<string>-
callback
<Function>err
<Error>addresses
<Object[]>
使用DNS协议处理邮件交换记录主机名(MX
记录)。adresses
参数是传递给callback
函数的主机名对象数组,对象包含priority
和exchange
属性(例如: [{priority: 10, exchange: 'mx.example.com'}, ...]
)。
dns.resolveNaptr(hostname, callback)#
hostname
<string>-
callback
<Function>err
<Error>addresses
<Object[]>
使用DNS协议来处理基于正则表达式匹配的记录(NAPTR
记录)的主机名。adresses
参数是传递给callback
函数的主机名对象数组,对象包含属性:
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[]>
使用DNS协议处理名称服务器主机名记录(NS
记录)。adresses
为有效的名称服务器记录主机名数组(eg:['ns1.example.com', 'ns2.example.com']
)。
dns.resolvePtr(hostname, callback)#
hostname
<string>-
callback
<Function>err
<Error>addresses
<string[]>
使用DNS协议处理主机名引用记录(PTR记录)。addresses
参数将一个字符串数组传递给回调函数callback
,其中包含回复记录。
dns.resolveSoa(hostname, callback)#
hostname
<string>-
callback
<Function>
使用DNS协议处理主机名子域名记录(SOA
记录)。addresses
参数为一个对象包含以下属性:
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[]>
使用DNS协议来处理主机名服务记录(SRV记录)。callback
函数返回的addresses
参数为对象数组,每个对象包含以下属性:
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}
使用DNS协议处理文本查询主机名(TXT记录)。回调函数callback
会返回records
参数,它是一个文本记录与主机名一一对应的二维数组(例如:[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]
).
每个数组文本块包含一条记录。根据用例,这些可以是连接在一起或单独对待。
dns.reverse(ip, callback)#
ip
<string>-
callback
<Function>err
<Error>hostnames
<string[]>
执行一个反向DNS查询返回IPv4或IPv6地址的主机名的数组。
出错情况下,err
是一个Error
对象,err.code
代码错误码。错误码列表:here.
dns.setServers(servers)#
servers
<string[]> array of rfc5952 formatted addresses
设置IP地址服务器端口在进行DNS解析时可用,servers
参数是一个rfc5952数组格式的地址。
如果端口是IANA默认端口(53),那么它可以被忽略。
比如:
dns.setServers([
'4.4.4.4',
'[2001:4860:4860::8888]',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053'
]);
ip
地址无效将会报错。
dns.setServers()
方法不要在DNS查询过程中使用。
DNS Promises API#
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('dns').promises
.
Class: dnsPromises.Resolver#
An independent resolver for DNS requests.
Note that creating a new resolver uses the default server settings. Setting
the servers used for a resolver using
resolver.setServers()
does not affect
other resolvers:
const { Resolver } = require('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');
})();
The following methods from the dnsPromises
API are available:
resolver.getServers()
resolver.resolve()
resolver.resolve4()
resolver.resolve6()
resolver.resolveAny()
resolver.resolveCname()
resolver.resolveMx()
resolver.resolveNaptr()
resolver.resolveNs()
resolver.resolvePtr()
resolver.resolveSoa()
resolver.resolveSrv()
resolver.resolveTxt()
resolver.reverse()
resolver.setServers()
dnsPromises.getServers()#
- Returns: <string[]>
Returns an array of IP address strings, formatted according to rfc5952, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.
[
'4.4.4.4',
'2001:4860:4860::8888',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053'
]
dnsPromises.lookup(hostname[, options])#
hostname
<string>-
family
<integer> The record family. Must be4
or6
. IPv4 and IPv6 addresses are both returned by default.hints
<number> One or more supportedgetaddrinfo
flags. Multiple flags may be passed by bitwiseOR
ing their values.all
<boolean> Whentrue
, thePromise
is resolved with all addresses in an array. Otherwise, returns a single address. Default:false
.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. Default: currentlyfalse
(addresses are reordered) but this is expected to change in the not too distant future. New code should use{ verbatim: true }
.
Resolves a hostname (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 IPv4
and IPv6 addresses are both returned if found.
With the all
option set to true
, the Promise
is resolved with addresses
being an array of objects with the properties address
and family
.
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 'ENOENT'
not only when
the hostname does not exist but also when the lookup fails in other ways
such as no available file descriptors.
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:
const dns = require('dns');
const dnsPromises = dns.promises;
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dnsPromises.lookup('example.com', options).then((result) => {
console.log('address: %j family: IPv%s', result.address, result.family);
// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
});
// When options.all is true, the result will be an Array.
options.all = true;
dnsPromises.lookup('example.com', options).then((result) => {
console.log('addresses: %j', result);
// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
});
dnsPromises.lookupService(address, port)#
Resolves the given address
and port
into a hostname and service using
the operating system's underlying getnameinfo
implementation.
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.
On error, the Promise
is rejected with an Error
object, where err.code
is the error code.
const dnsPromises = require('dns').promises;
dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
console.log(result.hostname, result.service);
// Prints: localhost ssh
});
dnsPromises.resolve(hostname[, rrtype])#
Uses the DNS protocol to resolve a hostname (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 contains | Result type | Shorthand method |
---|---|---|---|
'A' | IPv4 addresses (default) | <string> | dnsPromises.resolve4() |
'AAAA' | IPv6 addresses | <string> | dnsPromises.resolve6() |
'ANY' | any records | <Object> | dnsPromises.resolveAny() |
'CNAME' | canonical name records | <string> | dnsPromises.resolveCname() |
'MX' | mail exchange records | <Object> | dnsPromises.resolveMx() |
'NAPTR' | name authority pointer records | <Object> | dnsPromises.resolveNaptr() |
'NS' | name server records | <string> | dnsPromises.resolveNs() |
'PTR' | pointer records | <string> | dnsPromises.resolvePtr() |
'SOA' | start of authority records | <Object> | dnsPromises.resolveSoa() |
'SRV' | service records | <Object> | dnsPromises.resolveSrv() |
'TXT' | text records | <string[]> | dnsPromises.resolveTxt() |
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 to resolve.-
options
<Object>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.
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 to resolve.-
options
<Object>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.
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>
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:
Type | Properties |
---|---|
'A' | address /ttl |
'AAAA' | address /ttl |
'CNAME' | value |
'MX' | Refer to dnsPromises.resolveMx() |
'NAPTR' | Refer to dnsPromises.resolveNaptr() |
'NS' | value |
'PTR' | value |
'SOA' | Refer to dnsPromises.resolveSoa() |
'SRV' | Refer to dnsPromises.resolveSrv() |
'TXT' | This type of record contains an array property called entries which refers to dnsPromises.resolveTxt() , e.g. { 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.resolveCname(hostname)#
hostname
<string>
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>
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>
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>
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>
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>
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>
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>
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>
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of hostnames.
On error, the Promise
is rejected with an Error
object, where err.code
is one of the DNS error codes.
dnsPromises.setServers(servers)#
servers
<string[]> array of rfc5952 formatted addresses
Sets the IP address and port of servers to be used when performing DNS
resolution. The servers
argument is an array of rfc5952 formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.
dnsPromises.setServers([
'4.4.4.4',
'[2001:4860:4860::8888]',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053'
]);
An error will be thrown if an invalid address is provided.
The dnsPromises.setServers()
method must not be called while a DNS query is in
progress.
Note that this method works much like
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查询可以返回一个错误代码如下:
dns.NODATA
: DNS服务返回没有数据.dns.FORMERR
: DNS服务器查询没有格式化.dns.SERVFAIL
: DNS服务器返回失败。dns.NOTFOUND
: 域名未找到。dns.NOIMP
: DNS服务器不执行请求的操作。dns.REFUSED
: 查询DNS服务器拒绝。dns.BADQUERY
: 未格式化DNS查询。dns.BADNAME
: 未格式化主机名dns.BADFAMILY
: 没有提供地址族dns.BADRESP
: 未格式化DNS回复dns.CONNREFUSED
: 无法连接DNS服务器dns.TIMEOUT
: 连接DNS服务器超时dns.EOF
: 文件末尾dns.FILE
: 读取文件错误dns.NOMEM
: 内存溢出dns.DESTRUCTION
: 通道以及销毁dns.BADSTR
: 未格式化字符串dns.BADFLAGS
: 指定非法标记dns.NONAME
: 给定的主机名不是数字。dns.BADHINTS
: 指定非法的提示标志。dns.NOTINITIALIZED
:c-ares
异步DNS请求库初始化未完成。dns.LOADIPHLPAPI
: 加载iphlpapi.dll
(Windows IP辅助API应用程序接口模块)错误dns.ADDRGETNETWORKPARAMS
: 找不到GetNetworkParams
(读取本机DNS信息)函数dns.CANCELLED
: DNS查询取消
实现上的注意事项#
尽管dns.lookup()
和各种dns.resolve *()/ dns.reverse()
函数有相同的目标将网络的名字与网络地址联系在一起(反之亦然),他们的行为是完全不同的。
这些差异可以有微妙但重大影响着Node.js程序行为。
dns.lookup()
#
在底层,dns.lookup()
使用操作系统设施与大多数其他程序相同。例如,dns.lookup()
几乎总是解析给定的主机名与ping
命令一样。在许多类POSIX操作系统中,
dns.lookup()
函数的行为可以通过改变nsswitch.conf(5)
并且/或resolv.conf(5)
设置进行改变,但是需要注意改变这些文件就意味着改变所有正在这个操作系统中运行
的所有进程的行为。
尽管以异步JavaScript
的角度来调用dns.lookup()
,但在内部libuv
底层线程池中却是同步的调用getaddrinfo(3)
。
This can have surprising negative performance
implications for some applications, see the UV_THREADPOOL_SIZE
documentation for more information.
Note that various networking APIs will call dns.lookup()
internally to resolve
host names. If that is an issue, consider resolving the hostname to and 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*()` and `dns.reverse()`#
这些功能实现与dns.lookup()截然不同。它们不仅没有使用getaddrinfo(3)
并且通过网络执行DNS查询。使用异步网络通信,并且没有使用libuv线程池。
因此,这些函数不会像使用libuv线程池的dns.lookup()
函数一样会对其它进程有负面影响。
它们不像dns.lookup()
一样使用相同的配置文件。例如,它们不会使用来自/etc/hosts
配置。