A small package to cache DNS lookups in Node.js, with support for custom DNS servers and TTL (time-to-live) settings.
| Package Manager | Command |
|---|---|
| NPM | npm i dns-caching |
| Yarn | yarn add dns-caching |
| PNPM | pnpm add dns-caching |
Import the DnsCacheManager and initialize it with optional configurations:
import DnsCacheManager from 'dns-caching';
const dnsCacheManager = new DnsCacheManager({
cacheMaxEntries: 500, // Optional: Maximum number of entries in the cache
forceMaxTtl: -1, // Optional: Maximum TTL for cached entries in ms (-1 = no limit)
forceMinTtl: 0, // Optional: Minimum TTL for cached entries in ms
maxRetries: 3, // Optional: Maximum number of retries for DNS lookup
logger: console, // Optional: Custom logger
});Initialize the DNS cache manager to override the default dns.lookup function:
dnsCacheManager.initialize();This will intercept all DNS lookups made using the dns module and cache the results.
Use the lookup method to perform DNS lookups with caching:
async function performLookup(hostname) {
try {
const result = await dnsCacheManager.lookup(hostname);
console.log(`DNS Lookup Result for ${hostname}:`, result);
} catch (error) {
console.error(`DNS Lookup Error for ${hostname}:`, error);
}
}
performLookup('example.com');Retrieve statistics about the cache performance:
const stats = dnsCacheManager.getStats();
console.log('Cache Statistics:', stats);Clear the DNS cache for a specific hostname or for all entries:
// Clear cache for a specific hostname
dnsCacheManager.clearHostname('example.com');
// Clear the entire cache
dnsCacheManager.clear();Report network errors to the DNS cache manager to handle address switching:
dnsCacheManager.reportNetworkError('example.com');For advanced use cases, you can customize the behavior of the DNS cache manager by providing a custom logger or adjusting the retry logic:
const customLogger = {
debug: (message, meta) => console.debug(message, meta),
error: (message, meta) => console.error(message, meta),
};
const customDnsCacheManager = new DnsCacheManager({
logger: customLogger,
maxRetries: 3,
});This setup will help you efficiently manage DNS lookups with caching, improving the performance and reliability of your application.
Created by fallenbagel and packaged by gauthier-th
MIT © Seerr Team