Skip to content

Instantly share code, notes, and snippets.

@leegee
Created November 8, 2016 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leegee/508ee4bd97d7778b0ee28cba70b606e8 to your computer and use it in GitHub Desktop.
Save leegee/508ee4bd97d7778b0ee28cba70b606e8 to your computer and use it in GitHub Desktop.
Node DNS caching with Promises
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