dnsPromises.lookup(hostname[, options])
hostname<string>options<integer> | <Object>family<integer> 记录族。必须是4、6或0。值0表示同时返回 IPv4 和 IPv6 地址。默认值:0。hints<number> 一个或多个 支持的getaddrinfo标志。可以通过按位OR运算传递多个标志。all<boolean> 当为true时,Promise会返回包含所有地址的数组。否则,只返回一个地址。默认值:false。verbatim<boolean> 当值为true时,Promise会按 DNS 解析器返回的顺序解析 IPv4 和 IPv6 地址。 当值为false时,IPv4 地址会排在 IPv6 地址之前。 默认值: 当前为false(地址会被重新排序),但预计在不久的将来会发生变化。默认值可以通过dns.setDefaultResultOrder()或--dns-result-order配置。新代码应使用{ verbatim: true }。
将主机名(例如 '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 IPv4
and IPv6 addresses are both 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() 不一定与 DNS 协议有任何关系。该实现使用操作系统的功能,可以将名称与地址相互关联。此实现可能对任何 Node.js 程序的行为产生微妙但重要的影响。在使用 dnsPromises.lookup() 之前,请花一些时间查阅 实现考虑部分。
用法示例:
🌐 Example usage:
const dns = require('node: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}]
});