dns.resolve()方法是dns模塊的內置應用程序編程接口,用於將主機名解析為資源記錄的數組。
用法:
dns.resolve( hostname, rrtype, callback )
參數:此方法接受上述和以下所述的三個參數:
- hostname:此參數指定一個字符串,該字符串表示要解析的主機名。
- rrtype:它指定資源記錄類型。其默認值為“ A”。記錄列表(“ A”,“ AAAA”,“ ANY”,“ CNAME”,“ MX”,“ TXT”,“ NS”,“ NAPTR”,“ PTR”,“ SOA”,“ SRV”)是如下麵所描述的:
- A:IPv4地址
- AAAA:IPv6地址
- ANY:任何記錄
- CNAME:規範名稱記錄
- MX:郵件交換記錄
- NAPTR:名稱權限指針記錄
- NS:名稱服務器記錄
- PTR:指針記錄
- SOA:權限記錄的開始
- SRV:服務記錄
- TXT:文字記錄
- callback:它指定在主機名的DNS解析之後要調用的函數。
- error:如果生成,則指定錯誤。
- records:它是表示返回記錄的字符串或對象。
返回值:該方法返回錯誤,通過回調函數記錄,這些數據作為參數傳遞給回調函數。
以下示例說明了Node.js中dns.resolve()方法的使用:
範例1:
// Node.js program to demonstrate the
// dns.resolve() method
// Accessing dns module
const dns = require('dns');
// Set the rrtype for dns.resolve() method
const rrtype="A";
// Calling dns.resolve() method for hostname
// geeksforgeeks.org and print them in
// console as a callback
dns.resolve('geeksforgeeks.org', rrtype, (err, records)
=> console.log('records:%j', records));
Output:
records:["34.218.62.116"]
範例2:
// Node.js program to demonstrate the
// dns.resolve() method
// Accessing dns module
const dns = require('dns');
// Set the rrtype for dns.resolve() method
const rrtype="MX";
// Calling dns.resolve() method for hostname
// geeksforgeeks.org and print them in
// console as a callback
dns.resolve('geeksforgeeks.org', rrtype, (err, records)
=> console.log('records:%j', records));
輸出:
records:[ {"exchange":"alt1.aspmx.l.google.com", "priority":5}, {"exchange":"alt2.aspmx.l.google.com", "priority":5}, {"exchange":"aspmx.l.google.com", "priority":1}, {"exchange":"alt3.aspmx.l.google.com", "priority":10}, {"exchange":"alt4.aspmx.l.google.com", "priority":10} ]
範例3:
// Node.js program to demonstrate the
// dns.resolve() method
// Accessing dns module
const dns = require('dns');
// Set the rrtype for dns.resolve() method
const rrtype="TXT";
// Calling dns.resolve() method for hostname
// geeksforgeeks.org and print them in
// console as a callback
dns.resolve('geeksforgeeks.org', rrtype, (err,
records) => console.log('records:%j', records));
輸出:
records:[ ["v=spf1 include:amazonses.com include:_spf.google.com -all"], ["fob1m1abcdp777bf2ncvnjm08n"] ]
範例4:
// Node.js program to demonstrate the
// dns.resolve() method
// Accessing dns module
const dns = require('dns');
// Set the rrtype for dns.resolve() method
const rrtype="NS";
// Calling dns.resolve() method for hostname
// geeksforgeeks.org and print them in
// console as a callback
dns.resolve('geeksforgeeks.org', rrtype, (err,
records) => console.log('records:%j', records));
輸出:
records:[ "ns-1520.awsdns-62.org", "ns-1569.awsdns-04.co.uk", "ns-245.awsdns-30.com", "ns-869.awsdns-44.net" ]
注意:上麵的程序將通過使用node index.js
命令。
參考: https://nodejs.org/api/dns.html#dns_dns_resolve_hostname_rrtype_callback
相關用法
注:本文由純淨天空篩選整理自gekcho大神的英文原創作品 Node.js | dns.resolve() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。