diff --git a/lib/dns.js b/lib/dns.js index 5a1a0255db6cbe..82266effe908ed 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -134,21 +134,13 @@ function onlookupall(err, addresses) { } } -function cleanDnsCache() { +function cleanExpiredDnsCache() { + const currentTime = DateNow(); for (const key in dnsCache) { - delete dnsCache[key]; - } -} - -function scheduleCleanup() { - if (cleanupTimeout) { - return; + if (currentTime - dnsCache[key].timestamp >= 1000) { + delete dnsCache[key]; + } } - - cleanupTimeout = setTimeout(() => { - cleanDnsCache(); - cleanupTimeout = null; - }, 1000).ref(); } function addDnsEntry(cacheKey, address, family) { @@ -158,7 +150,7 @@ function addDnsEntry(cacheKey, address, family) { timestamp: DateNow(), }; - scheduleCleanup(); + cleanExpiredDnsCache(); return dnsCache[cacheKey]; } @@ -175,6 +167,7 @@ function lookup(hostname, options, callback) { let all = false; let verbatim = getDefaultVerbatim(); + cleanExpiredDnsCache(); // Parse arguments if (hostname) { @@ -248,7 +241,7 @@ function lookup(hostname, options, callback) { const cacheKey = `${hostname}_${family || 'default'}`; const cachedResult = dnsCache[cacheKey]; - if (cachedResult && DateNow() - cachedResult.timestamp < 1000) { + if (cachedResult) { callback(null, cachedResult.address, cachedResult.family); return {}; }