quake3 server connector | ssh remote wget | remove ctrl characters | Search

The lookupDNS function, a JavaScript module, performs a DNS lookup on a given IP address and caches the result for subsequent lookups. It uses the dns module to asynchronously retrieve the DNS information, and returns the cached or newly looked-up result as a promise.

Run example

npm run import -- "dns lookup"

dns lookup

var dns = require('dns')
var _dnsLookup = {}

async function lookupDNS(address) {
  if(typeof _dnsLookup[address] != 'undefined')
    return _dnsLookup[address]
  return new Promise((resolve, reject) => dns.lookup(address, function(err, dstIP) {
    if(err) {
      return reject(err)
    }
    _dnsLookup[address] = dstIP
    return resolve(dstIP)
  }))
}

module.exports = lookupDNS

What the code could have been:

// dns-lookup.js
const dns = require('dns');

// Cache DNS lookups to avoid redundant requests
const dnsCache = {};

/**
 * Performs a DNS lookup on the given address and returns the result as a promise.
 * If the result is already cached, it returns the cached value.
 * @param {string} address - The IP address or hostname to perform the DNS lookup on.
 * @returns {Promise} A promise that resolves to the destination IP address.
 */
async function lookupDNS(address) {
  // Check if the result is already cached
  if (dnsCache[address]) {
    return dnsCache[address];
  }

  // Perform the DNS lookup using dns.lookup
  try {
    const dstIP = await new Promise((resolve, reject) => {
      dns.lookup(address, (err, ip) => {
        if (err) {
          reject(err);
        } else {
          dnsCache[address] = ip;
          resolve(ip);
        }
      });
    });

    // Store the result in the cache
    dnsCache[address] = dstIP;

    return dstIP;
  } catch (error) {
    // If there's an error, remove the cached result to prevent stale data
    delete dnsCache[address];
    throw error;
  }
}

module.exports = lookupDNS;

DNS Lookup Function

Overview

This JavaScript code exports a function lookupDNS that performs a DNS lookup on a given IP address.

Code Breakdown

Variables

Function: lookupDNS(address)

Usage

This function can be used to perform DNS lookups, with the result being cached for subsequent lookups with the same address.