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 🙏

© 2026 – Pkg Stats / Ryan Hefner

dorrat-cache

v3.0.0

Published

Ultra-ligero cache in-memory (TTL/LRU/LFU) con persistencia opcional, TTL adaptativo y estrategia pluggable.

Readme

🧠 DorratCache

DorratCache es una caché adaptable en memoria con soporte para estrategias de eliminación (LRU, LFU), TTL dinámico, persistencia opcional y compatibilidad total con CommonJS y ESM.

🚀 Ideal para bots, middleware, rate-limiters, sesiones y cualquier otro uso que necesite una caché inteligente, flexible y veloz.


📦 Requisitos

  • Node.js v18 o superior
  • Acceso a fs/promises y path (vienen con Node)

✨ Características

  • ✅ TTL (tiempo de vida) por clave
  • ♻️ Adaptación automática del TTL según frecuencia de uso
  • 🧠 Estrategia de eliminación:
    • LRU: Least Recently Used (por defecto)
    • LFU: Least Frequently Used
  • 💾 Persistencia opcional en disco (JSON)
  • 🔧 Compatible con ESM y CommonJS
  • 🔥 Sistema de eventos (set, hit, del, clear, evict)
  • 🛠️ Tipado completo en TypeScript (.d.ts incluido)

🔰 Uso Básico (ESM)

// ESM
import DorratCache from 'dorrat-cache';

const cache = await DorratCache.create({
  max: 100,
  ttl: 60000,
  strategy: 'lru',
  adaptive: true,
  persistence: './cache.json'
});

cache.set('clave', 'valor');
console.log(cache.get('clave')); // "valor"

🔰 Uso Básico (CommonJS)

// CommonJS
const { DorratCache } = require('dorrat-cache');

const cache = await DorratCache.create({
  max: 100,
  ttl: 60000,
  strategy: 'lfu',
  adaptive: true,
  persistence: './cache.json'
});

cache.set('clave', 'valor');
console.log(cache.get('clave')); // "valor"

🧪 API Pública

new DorratCache(options)

| Opción | Tipo | Default | Descripción | |--------------|-------------------|--------------|-----------------------------------------| | max | number | 256 | Máximo de entradas almacenadas | | ttl | number (ms) | 60000 | Tiempo de vida por defecto por clave | | strategy | 'lru' / 'lfu' / función personalizada | 'lru' | Estrategia de eliminación | | adaptive | boolean | true | Aumenta TTL según frecuencia de acceso | | persistence| boolean \| string | false | Guarda y restaura caché desde disco | | serializer | (data) => string | JSON.stringify | Serializador personalizado | | deserializer | (raw) => data | JSON.parse | Deserializador personalizado | | debounce | number | 500 | Tiempo de espera para guardar (ms) | | evictionRate | number | 1 | Número de entradas a desalojar extra |


Métodos

| Método | Descripción | |----------------------|---------------------------------------------------------| | set(key, val, ttl?)| Guarda un valor con TTL opcional | | get(key, def?) | Obtiene un valor, actualiza hits y TTL si aplica | | has(key) | Retorna true si la clave existe y no ha expirado | | ttl(key) | Retorna el tiempo restante en ms o -1 si no existe | | delete(key) | Elimina una entrada manualmente | | clear() | Limpia toda la caché | | size() | Retorna la cantidad de claves actuales | | keys() | Lista de claves actuales | | values() | Lista de valores actuales | | entries() | Lista de pares [clave, valor] | | snapshot() | Dump actual (serializable) de todo el contenido | | [Symbol.iterator] | Iterador para usar en for...of | | with(key, fn, ttl?) | Devuelve valor si existe o lo genera y guarda | | stop() | Detiene el guardado automático | | stats | Objeto con estadísticas: hits, misses, evictions |


📈 Métricas y extensiones

console.log(cache.stats);
// { hits: 5, misses: 2, evictions: 1 }

await cache.with('user-123', () => getUserFromDB(), 10000);

📡 Eventos

Puedes usar .on() para reaccionar a eventos:

cache.on('set', (key, val) => {
  console.log(`📝 Seteado: ${key} =`, val);
});

cache.on('hit', (key, val) => {
  console.log(`🎯 Cache hit: ${key}`);
});

cache.on('del', key => {
  console.log(`🗑️ Eliminado: ${key}`);
});

cache.on('evict', key => {
  console.log(`🚮 Evictado: ${key}`);
});

📚 Ejemplo con TTL adaptativo y persistencia

const cache = new DorratCache({
  ttl: 30000,
  adaptive: true,
  persistence: './session-cache.json'
});

cache.set('user123', { online: true });

// Simula acceso frecuente:
setInterval(() => {
  cache.get('user123');
  console.log('TTL:', cache.ttl('user123'));
}, 5000);

🗂 Estructura del Proyecto

📁 dorrat-cache
├── esm/
│   └── index.js       → Versión ESM
├── cjs/
│   └── index.cjs      → Versión CommonJS
├── types/
│   └── index.d.ts     → Tipado TypeScript
└── package.json       → Metadata del paquete

🧠 Pensado para...

  • Bots (WhatsApp, Discord, Telegram)
  • APIs y middleware
  • Rate-limiting / anti-spam
  • Sistemas temporales / TTL
  • Caches interactivas con persistencia

📜 Licencia

MIT — Hecho con 💖 por DIEGO-OFC


📦 Instalar

npm install dorrat-cache

💡 Tip

Puedes acceder a la caché como un iterable:

for (const [key, value] of cache) {
  console.log(key, value);
}

DorratCache: Simple y rápido.