cache-light
v1.0.2
Published
Lightweight, high-performance smart cache for Node.js with async function support, TTL, and optional persistence.
Maintainers
Readme
cache-light
Lightweight, high-performance caching library for Node.js with TTL support and async function caching.
Features
- ⚡ In-memory caching
- ⏱️ TTL (Time-To-Live) support
- 🔁 Async function result caching
- 🧠 Custom cache key generation
- 🧹 Auto cleanup of expired entries
- 📦 Zero dependencies
- 🧩 ES Modules support
Installation
npm install cache-lightUsage
import smartCache from 'cache-light';for basic cache
smartCache.set('key', 'value', 5000);
console.log(smartCache.get('key')); // value
smartCache.del('key');
smartCache.clear();for async function cache
const fetchData = smartCache.cacheAsync(async () => {
console.log('Fetching data...');
return { data: 'Hello World' };
}, { ttl: 10000 }); // cached for 10s
await fetchData(); // fetches
await fetchData(); // cachedauto cleanup
smartCache.enableAutoCleanup(30000);Example One:
// Basic cache
smartCache.set('Hi', 'Glad', 5000);
console.log(smartCache.get('Glad'));
// Async function cache
const fetchData = smartCache.cacheAsync(async id => {
console.log('Fetching data for', id);
return { id, data: `Data for ${id}` };
}, { ttl: 10000 });
(async () => {
console.log(await fetchData(1)); // Fetches
console.log(await fetchData(1)); // Cached
})();
// Enable automatic cleanup every 30 seconds
smartCache.enableAutoCleanup(30000);Example Two:
const fetchUsers = smartCache.cacheAsync(async () => {
console.log('Calling API...');
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await res.json();
return data;
}, { ttl: 10000 }); // cache for 10 seconds
// Run multiple times
async function run() {
console.log('First call:');
console.log(await fetchUsers());
console.log('\nSecond call (should be cached):');
console.log(await fetchUsers());
console.log('\nWaiting 11 seconds...');
setTimeout(async () => {
console.log('\nThird call (cache expired):');
console.log(await fetchUsers());
}, 11000);
}
run();Example Three:
const fetchUserById = smartCache.cacheAsync(
async (id) => {
console.log(`Fetching user ${id}...`);
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
return res.json();
},
{
ttl: 10000,
keyGenerator: ([id]) => `user:${id}`
}
);
// Usage
// API call
console.log(await fetchUserById(1));
// from Cache Memory
console.log(await fetchUserById(1));
// New API call
console.log(await fetchUserById(2)); API
- set(key, value, ttl)
- Store a value with optional TTL (in ms)
- get(key)
- Retrieve cached value
- del(key)
- Delete a key
- clear()
- Clear entire cache
- cacheAsync(fn, options)
- Cache async function results
- Options:
- ttl > cache duration (ms)
- keyGenerator > custom key logic
- enableAutoCleanup(interval)
- Automatically removes expired entriesRequirements
- Node.js >= 16
- ES Modules ("type": "module")License
MIT © [GladsonRouth]
