Created
November 8, 2016 09:21
-
-
Save leegee/508ee4bd97d7778b0ee28cba70b606e8 to your computer and use it in GitHub Desktop.
Node DNS caching with Promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dns = require('dns'), cache = {}; | |
dns._lookup = dns.lookup; | |
dns.lookup = function(domain) { | |
return new Promise( (resolve, reject) => { | |
var key = domain; | |
if (key in cache) { | |
var ip = cache[key], | |
ipv = ip.indexOf('.') !== -1 ? 4 : 6; | |
return process.nextTick(function() { | |
resolve(ip); | |
}); | |
} | |
dns._lookup(domain, null, function(err, ip, ipv) { | |
if (err) reject(err); | |
cache[key] = ip; | |
resolve(ip); | |
}); | |
}); | |
}; | |
dns.lookup('google.com').then( (ip) => { | |
console.log( ip ); | |
}).catch( (err) => { | |
console.error( err ); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment