Introduction to `cacheable-lookup`
The `cacheable-lookup` module is a robust and efficient DNS caching library for Node.js applications. By utilizing it, developers can significantly optimize DNS queries and improve application performance. In this post, we’ll dive deep into the `cacheable-lookup` library, explaining its numerous APIs and showcasing practical examples.
API Explanations and Examples
1. Installation
npm install cacheable-lookup
2. Basic Usage
const CacheableLookup = require('cacheable-lookup');
const cacheable = new CacheableLookup();
// Example
cacheable.lookup('example.com', (err, address, family) => {
console.log('address:', address);
console.log('family:', family);
});
3. Advanced Usage with Got and Https
const got = require('got');
const https = require('https');
const CacheableLookup = require('cacheable-lookup');
const cacheable = new CacheableLookup();
const agent = new https.Agent({
lookup: cacheable.lookup
});
(async () => {
const response = await got('https://example.com', { agent });
console.log(response.body);
})();
4. Configuring CacheableLookup
const cacheable = new CacheableLookup({
maxTtl: 60, // Maximum time to live in seconds
minTtl: 10, // Minimum time to live in seconds
errorTtl: 0.5 // Time to live for errors in seconds
});
5. Clear Cache
cacheable.cache.clear();
Application Example
Here’s a complete example of how `cacheable-lookup` can be integrated into a Node.js application to improve DNS resolution efficiency.
const http = require('http');
const CacheableLookup = require('cacheable-lookup');
const cacheable = new CacheableLookup();
const server = http.createServer((req, res) => {
cacheable.lookup('example.com', (err, address) => {
if (err) {
res.writeHead(500);
res.end('Error with DNS lookup');
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Resolved Address: ' + address);
}
});
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
By integrating `cacheable-lookup`, your applications can benefit from quicker DNS resolutions, ensuring smoother and more efficient network operations.
Conclusion
`cacheable-lookup` is a highly beneficial library for Node.js developers, offering advanced DNS caching capabilities. With this guide, you should be able to integrate it into your own projects effectively.
Hash: 2cdf13dafc752d4a0addd4ce2c5e8f72503e394d061585a89a695914b053246c