A simple in-memory cache for Node.js with put(), get(), del(), and timeout functionality
npx @tessl/cli install tessl/npm-memory-cache@0.2.0Memory Cache is a simple in-memory caching solution for Node.js applications that provides efficient storage and retrieval of key-value pairs with optional time-based expiration. It features automatic cleanup through setTimeout-based expiration, debugging capabilities with hit/miss tracking, and both a default singleton instance and Cache constructor for creating multiple independent cache instances.
npm install memory-cacheconst cache = require('memory-cache');For creating multiple cache instances:
const { Cache } = require('memory-cache');
const myCache = new Cache();Alternative destructuring syntax:
const cache = require('memory-cache');
const { Cache } = cache;
const myCache = new Cache();const cache = require('memory-cache');
// Store a value
cache.put('user:123', { name: 'John', age: 30 });
// Retrieve a value
const user = cache.get('user:123');
console.log(user); // { name: 'John', age: 30 }
// Store with expiration (5 seconds)
cache.put('temp', 'temporary data', 5000);
// Store with expiration and callback
cache.put('session', 'active', 10000, function(key, value) {
console.log(key + ' expired with value: ' + value);
});
// Delete a value
cache.del('user:123');
// Clear all values
cache.clear();Fundamental caching operations for storing, retrieving, and managing cached data.
/**
* Stores a key-value pair with optional expiration and timeout callback
* @param {string} key - Cache key
* @param {*} value - Value to cache
* @param {number} [time] - Expiration time in milliseconds
* @param {function} [timeoutCallback] - Callback fired when entry expires
* @returns {*} The cached value
* @throws {Error} If time is not a positive number or timeoutCallback is not a function
*/
put(key, value, time, timeoutCallback)
/**
* Retrieves a cached value by key
* @param {string} key - Cache key to retrieve
* @returns {*|null} Cached value or null if not found/expired
*/
get(key)
/**
* Deletes a cached entry by key
* @param {string} key - Cache key to delete
* @returns {boolean} True if the key was successfully deleted, false otherwise
*/
del(key)
/**
* Removes all entries from the cache and clears all timeouts
*/
clear()Methods for inspecting cache state and retrieving metadata about cached entries.
/**
* Returns the current number of entries in the cache
* @returns {number} Current cache size
*/
size()
/**
* Returns the number of entries taking up space in the cache
* May differ from size() if setTimeout removal fails
* @returns {number} Memory size count
*/
memsize()
/**
* Returns an array of all cache keys
* @returns {string[]} All cache keys
*/
keys()Debug functionality and performance monitoring for cache operations.
/**
* Enables or disables debug mode for hit/miss tracking
* @param {boolean} bool - Enable (true) or disable (false) debug mode
*/
debug(bool)
/**
* Returns the number of cache hits (only tracked in debug mode)
* @returns {number} Hit count
*/
hits()
/**
* Returns the number of cache misses (only tracked in debug mode)
* @returns {number} Miss count
*/
misses()Data persistence and transfer capabilities for cache contents.
/**
* Exports all cache data as a JSON string (excludes timeout callbacks)
* @returns {string} JSON representation of cache data
*/
exportJson()
/**
* Imports cache data from a JSON string (from previous exportJson call)
* Expired entries are automatically removed during import
* @param {string} jsonToImport - JSON string to import
* @param {object} [options] - Import options
* @param {boolean} [options.skipDuplicates=false] - Skip duplicate keys if true
* @returns {number} New cache size after import
*/
importJson(jsonToImport, options)Creates new independent cache instances for isolation and multi-tenancy.
/**
* Cache constructor for creating new independent cache instances
* @constructor
*/
function Cache()const cache = require('memory-cache');
// Store simple values
cache.put('config', { theme: 'dark', lang: 'en' });
cache.put('counter', 42);
// Retrieve values
const config = cache.get('config');
const counter = cache.get('counter');
// Check cache size
console.log('Cache has', cache.size(), 'entries');
// List all keys
console.log('Keys:', cache.keys());const cache = require('memory-cache');
// Store with 30-second expiration
cache.put('session:abc123', { userId: 456, role: 'admin' }, 30000);
// Store with expiration and cleanup callback
cache.put('temp:processing', { status: 'active' }, 5000, function(key, value) {
console.log('Processing job', key, 'expired');
// Perform cleanup operations
});
// Check if value is still cached
setTimeout(() => {
const session = cache.get('session:abc123');
if (session) {
console.log('Session still active');
} else {
console.log('Session expired');
}
}, 35000);const { Cache } = require('memory-cache');
// Create separate caches for different purposes
const userCache = new Cache();
const productCache = new Cache();
// Each cache operates independently
userCache.put('active', ['user1', 'user2']);
productCache.put('active', ['prod1', 'prod2']);
console.log('Users:', userCache.get('active'));
console.log('Products:', productCache.get('active'));
// Enable debugging on specific cache
userCache.debug(true);
userCache.get('active'); // Counts as hit
userCache.get('missing'); // Counts as miss
console.log('User cache hits:', userCache.hits());
console.log('User cache misses:', userCache.misses());const cache = require('memory-cache');
// Populate cache
cache.put('user:1', { name: 'Alice' });
cache.put('user:2', { name: 'Bob' });
cache.put('temp', 'expires soon', 1000);
// Export cache data
const exported = cache.exportJson();
console.log('Exported:', exported);
// Clear cache and import data back
cache.clear();
const importedSize = cache.importJson(exported);
console.log('Imported', importedSize, 'entries');
// Import with skip duplicates option
const moreData = '{"user:3":{"value":{"name":"Charlie"},"expire":"NaN"}}';
cache.importJson(moreData, { skipDuplicates: true });/**
* Options object for importJson method
* @typedef {object} ImportOptions
* @property {boolean} [skipDuplicates=false] - Skip duplicate keys during import
*/
/**
* Timeout callback function signature
* @callback TimeoutCallback
* @param {string} key - The key that expired
* @param {*} value - The value that was cached
*/The cache methods can throw errors in the following situations:
put() throws Error if time parameter is not a positive numberput() throws Error if timeoutCallback parameter is not a functionimportJson() will throw if JSON parsing fails due to invalid JSON formatconst cache = require('memory-cache');
try {
// This will throw an error
cache.put('key', 'value', -100); // Negative time
} catch (error) {
console.error('Cache error:', error.message);
}
try {
// This will throw an error
cache.put('key', 'value', 1000, 'not a function');
} catch (error) {
console.error('Cache error:', error.message);
}