diff --git a/lib/dns.js b/lib/dns.js index 681f0aa3e58ecf..a2b4a203abe9d9 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -133,10 +133,32 @@ function onlookupall(err, addresses) { } } +function cleanExpiredDnsCache() { + const currentTime = DateNow(); + for (const key in dnsCache) { + if (currentTime - dnsCache[key].timestamp >= 1000) { + dnsCache[key] = undefined; + } + } +} + +function addDnsEntry(cacheKey, address, family) { + dnsCache[cacheKey] = { + address, + family, + timestamp: DateNow(), + }; + + cleanExpiredDnsCache(); + + return dnsCache[cacheKey]; +} // Easy DNS A/AAAA look up // lookup(hostname, [options,] callback) const validFamilies = [0, 4, 6]; +const dnsCache = { __proto__: null }; +const { DateNow } = primordials; function lookup(hostname, options, callback) { let hints = 0; let family = 0; @@ -212,8 +234,22 @@ function lookup(hostname, options, callback) { return {}; } + const cacheKey = `${hostname}_${family || 'default'}_${all ? 'all' : 'single'}`; + const cachedResult = dnsCache[cacheKey]; + + if (cachedResult) { + cleanExpiredDnsCache(); + callback(null, cachedResult.address, cachedResult.family); + return {}; + } + const req = new GetAddrInfoReqWrap(); - req.callback = callback; + req.callback = (error, address, family) => { + if (!error) { + addDnsEntry(cacheKey, address, family); + } + callback(error, address, family); + }; req.family = family; req.hostname = hostname; req.oncomplete = all ? onlookupall : onlookup;