node-cache-lite
v1.0.0
Published
A lightweight, in-memory cache library for Node.js with TTL support
Maintainers
Readme
node-cache-lite
A lightweight, high-performance in-memory cache for Node.js with TTL (Time To Live), automatic eviction, and zero dependencies.
Designed for MVPs, small SaaS applications, APIs, and microservices where Redis introduces unnecessary complexity.
Features
- Lightweight and fast in-memory caching
- TTL (Time To Live) support per key
- Optional maximum cache size with automatic eviction
- Built-in cache statistics (hits, misses, evictions)
getOrSet()helper for the cache-aside pattern- Batch operations (
setMultiple,getMultiple,deleteMultiple) - First-class TypeScript support
- Zero dependencies
- Fully tested
Installation
npm install node-cache-liteor
yarn add node-cache-liteQuick Start
import { createCache } from "node-cache-lite";
const cache = createCache();
cache.set("key", "value");
const value = cache.get("key");
cache.has("key");
cache.delete("key");
cache.clear();Time To Live (TTL)
const cache = createCache();
cache.set("sessionId", "abc123", 5000);
console.log(cache.get("sessionId"));
setTimeout(() => {
console.log(cache.get("sessionId"));
}, 5001);TTL is defined per key. Expired entries are removed lazily to avoid unnecessary background timers.
Configuration Options
const cache = createCache({
maxSize: 100
});CacheOptions
| Option | Type | Description | |--------|--------|-------------| | maxSize | number | Maximum number of entries allowed in the cache |
When the maximum size is reached, the oldest entries are evicted automatically.
API Reference
createCache(options?: CacheOptions): CacheInstance
Creates a new cache instance.
cache.set(key: string, value: T, ttl?: number): void
Stores a value in the cache.
cache.get(key: string): T | undefined
Retrieves a value from the cache.
cache.has(key: string): boolean
Checks whether a key exists and is not expired.
cache.delete(key: string): boolean
Deletes a key from the cache.
cache.clear(): void
Removes all entries from the cache.
cache.size(): number
Returns the number of entries currently stored.
cache.getOrSet(key: string, fallback: () => Promise | T, ttl?: number): Promise
Implements the cache-aside pattern.
Batch Operations
cache.setMultiple([
["a", 1],
["b", 2]
]);
const values = cache.getMultiple(["a", "b"]);
cache.deleteMultiple(["a", "b"]);Cache Statistics
cache.stats();Returns:
{
hits: number;
misses: number;
evictions: number;
}Testing
npm testLicense
MIT
