npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

dns-cache-resolver

v1.0.6

Published

A parametrizable DNS cache for Node.js

Downloads

428

Readme

dns-cache-resolver

dns-cache-resolver is a lightweight, performant DNS caching library for Node.js, designed with TypeScript for robust and type-safe applications. 🚀

Why Use dns-cache-resolver? 🧐

  • Boost Performance: Reduce repetitive DNS lookups with in-memory caching.
  • Customizable: Configure cache behavior with flexible TTL and size options.
  • TypeScript First: Enjoy the benefits of type safety and IDE autocompletion.
  • Plug-and-Play: Simple to integrate into existing applications.

Features ✨

  • Configurable TTL 🕒: Set the time-to-live for cache entries.
  • Maximum Entries 📦: Control the number of entries in the cache.
  • In-Memory Caching 🧠: Speed up DNS resolutions with fast, local cache storage.
  • IPv4 and IPv6 Support 🌍: Resolve addresses for both address families.
  • Timeout Handling ⏱️: Avoid slow lookups with built-in resolution timeouts.

Installation ⚙️

Install via npm:

npm install dns-cache-resolver

Usage 📘

Here’s a quick example:

import { DnsCache } from 'dns-cache-resolver';

// Initialize the DNS cache
const dnsCache = new DnsCache({
  ttl: 60000, // Cache entries live for 60 seconds
  maxEntries: 100, // Maximum of 100 cache entries
});

// Resolve a hostname and cache the result
const ip = await dnsCache.resolve('example.com');
console.log(`IP Address: ${ip}`);

Configuration Options 🛠️

| Option | Type | Default | Description | |-------------|---------|---------|----------------------------------------------------------| | ttl | number | 60000 | Time-to-live for cache entries in milliseconds. | | maxEntries| number | 1000 | Maximum number of entries allowed in the cache. |

Examples 💡

Basic Usage

import { DnsCache } from 'dns-cache-resolver';

const dnsCache = new DnsCache({
  ttl: 30000, // 30 seconds TTL
  maxEntries: 50, // Limit to 50 cache entries
});

async function getIp(hostname: string) {
  try {
    const ip = await dnsCache.resolve(hostname);
    console.log(`Resolved IP for ${hostname}: ${ip}`);
  } catch (error) {
    console.error(`Error resolving ${hostname}:`, error.message);
  }
}

getIp('example.com');
getIp('nodejs.org');

IPv4 and IPv6 Support

const ipV4 = await dnsCache.resolve('example.com', 4); // IPv4
console.log(`IPv4: ${ipV4}`);

const ipV6 = await dnsCache.resolve('example.com', 6); // IPv6
console.log(`IPv6: ${ipV6}`);

Integrating with Axios 🌐

You can use dns-cache-resolver with Axios to enhance performance and avoid DNS overhead:

import axios from 'axios';
import { DnsCache } from 'dns-cache-resolver';

const dnsCache = new DnsCache({
  ttl: 30000,
  maxEntries: 100,
});

// Create an Axios instance
const axiosInstance = axios.create();

// Add a DNS resolution interceptor
axiosInstance.interceptors.request.use(
  async config => {
    const url = new URL(config.url || '');
    const hostname = url.hostname;

    try {
      const ip = await dnsCache.resolve(hostname);
      config.url = config.url.replace(hostname, ip);
    } catch (error) {
      console.error(`Failed to resolve DNS for ${hostname}: ${error.message}`);
    }

    return config;
  },
  error => Promise.reject(error)
);

// Make a request
axiosInstance
  .get('https://example.com/api/data')
  .then(response => console.log('Response:', response.data))
  .catch(error => console.error('Error:', error));

Clearing Cache

dnsCache.clear(); // Remove all cached entries
dnsCache.remove('example.com', 4); // Remove specific entry for IPv4

Listing Cache Entries

const entries = dnsCache.list();
entries.forEach(([key, value]) => {
  console.log(`Key: ${key}, Address: ${value.address}, Expires At: ${value.expiresAt}`);
});

Contributing 🤝

We’re excited to have your contributions! Whether it’s fixing bugs, adding features, or improving documentation, feel free to open issues or submit pull requests on GitHub.

How to Contribute

  1. Fork the repository.
  2. Create a feature branch (git checkout -b feature/your-feature).
  3. Commit your changes (git commit -m 'Add some feature').
  4. Push to your branch (git push origin feature/your-feature).
  5. Open a pull request.

License 📄

This project is licensed under the MIT License. See the LICENSE file for more details.

Contact 📬

For questions, feedback, or suggestions, reach out to Alex Silva.

Acknowledgements 🙏

A huge thanks to our contributors and users for their continuous support and feedback!