min-cache
v0.1.5
Published
Ultra-lightweight in-memory cache with TTL
Downloads
25
Readme
MinCache
Ultra-lightweight, in-memory cache for Node.js with TTL support and configurable size limits.
Features
- In-memory storage for fast access
- Time-to-live (TTL) for each record (ms)
- Max cache size (in KB) with automatic clearing oldest or expired records
- Customizable options (debug, TTL, cleanup interval)
- Redis-like method names (
SET,GET,DEL, etc.) - TypeScript support
Installation
npm install min-cacheUsage
import MinCache from 'min-cache';
const cache = new MinCache('myCache', {
maxSizeKb: 5 * 1024, // Max cache size in KB
clearExpiredMs: 60000, // Clear interval
ttlMs: 30000, // Default TTL for items (ms)
debug: true // On/Off logging
});
// Add an item
cache.set('key', { foo: 'bar' }, 10000); // TTL: 10s
// Get an item
const value = cache.get('key');
// Check if a key exists
const exists = cache.exists('key');
// Remove a key
cache.del('key');
// Get list of all keys
const keys = cache.keys();
// Get all valid items
const all = cache.getAll();
// Set a new TTL for a key
cache.setTtl('key', 20000); // exact 20 seconds from now
// Find up all keys starting with "userid"
const matches = cache.scan('user*');
// Find up maximum 10 keys starting with "userid"
const matchesLimited = cache.scan('user*', 10);API
Constructor
new MinCache(id: string, options?: CacheOptions)id: Unique cache name (for logging/debugging)options:maxSizeKb(number): Max cache size in KB (default: 5000)clearExpiredMs(number): How often to clear expired items (default: 10000)ttlMs(number): Default TTL for items in ms (default: 60000)debug(boolean): Enable debug logging (default: false)
Methods
set(key, value, ttlMs?): Add item with optional TTLget(key): Get item by keyexists(key): Check if key exists and is not expireddel(key): Remove item by keydelAll(): Remove all itemsdelExpired(): Remove all expired itemskeys(): Get all valid keysgetAll(): Get all valid itemsttl(key): Get time-to-live (seconds) for a keysetTtl(key, ttlMs): Set new TTL for a keyrename(oldKey, newKey): Rename a keyscan(pattern, count?): Get up tocountkeys matching a pattern (e.g.userid*). Returns an array of matching keys.
