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.00
# Memory Cache
1
2
Memory 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.
3
4
## Package Information
5
6
- **Package Name**: memory-cache
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install memory-cache`
10
11
## Core Imports
12
13
```javascript
14
const cache = require('memory-cache');
15
```
16
17
For creating multiple cache instances:
18
19
```javascript
20
const { Cache } = require('memory-cache');
21
const myCache = new Cache();
22
```
23
24
Alternative destructuring syntax:
25
26
```javascript
27
const cache = require('memory-cache');
28
const { Cache } = cache;
29
const myCache = new Cache();
30
```
31
32
## Basic Usage
33
34
```javascript
35
const cache = require('memory-cache');
36
37
// Store a value
38
cache.put('user:123', { name: 'John', age: 30 });
39
40
// Retrieve a value
41
const user = cache.get('user:123');
42
console.log(user); // { name: 'John', age: 30 }
43
44
// Store with expiration (5 seconds)
45
cache.put('temp', 'temporary data', 5000);
46
47
// Store with expiration and callback
48
cache.put('session', 'active', 10000, function(key, value) {
49
console.log(key + ' expired with value: ' + value);
50
});
51
52
// Delete a value
53
cache.del('user:123');
54
55
// Clear all values
56
cache.clear();
57
```
58
59
## Capabilities
60
61
### Core Cache Operations
62
63
Fundamental caching operations for storing, retrieving, and managing cached data.
64
65
```javascript { .api }
66
/**
67
* Stores a key-value pair with optional expiration and timeout callback
68
* @param {string} key - Cache key
69
* @param {*} value - Value to cache
70
* @param {number} [time] - Expiration time in milliseconds
71
* @param {function} [timeoutCallback] - Callback fired when entry expires
72
* @returns {*} The cached value
73
* @throws {Error} If time is not a positive number or timeoutCallback is not a function
74
*/
75
put(key, value, time, timeoutCallback)
76
77
/**
78
* Retrieves a cached value by key
79
* @param {string} key - Cache key to retrieve
80
* @returns {*|null} Cached value or null if not found/expired
81
*/
82
get(key)
83
84
/**
85
* Deletes a cached entry by key
86
* @param {string} key - Cache key to delete
87
* @returns {boolean} True if the key was successfully deleted, false otherwise
88
*/
89
del(key)
90
91
/**
92
* Removes all entries from the cache and clears all timeouts
93
*/
94
clear()
95
```
96
97
### Cache Information
98
99
Methods for inspecting cache state and retrieving metadata about cached entries.
100
101
```javascript { .api }
102
/**
103
* Returns the current number of entries in the cache
104
* @returns {number} Current cache size
105
*/
106
size()
107
108
/**
109
* Returns the number of entries taking up space in the cache
110
* May differ from size() if setTimeout removal fails
111
* @returns {number} Memory size count
112
*/
113
memsize()
114
115
/**
116
* Returns an array of all cache keys
117
* @returns {string[]} All cache keys
118
*/
119
keys()
120
```
121
122
### Debug and Statistics
123
124
Debug functionality and performance monitoring for cache operations.
125
126
```javascript { .api }
127
/**
128
* Enables or disables debug mode for hit/miss tracking
129
* @param {boolean} bool - Enable (true) or disable (false) debug mode
130
*/
131
debug(bool)
132
133
/**
134
* Returns the number of cache hits (only tracked in debug mode)
135
* @returns {number} Hit count
136
*/
137
hits()
138
139
/**
140
* Returns the number of cache misses (only tracked in debug mode)
141
* @returns {number} Miss count
142
*/
143
misses()
144
```
145
146
### Import/Export
147
148
Data persistence and transfer capabilities for cache contents.
149
150
```javascript { .api }
151
/**
152
* Exports all cache data as a JSON string (excludes timeout callbacks)
153
* @returns {string} JSON representation of cache data
154
*/
155
exportJson()
156
157
/**
158
* Imports cache data from a JSON string (from previous exportJson call)
159
* Expired entries are automatically removed during import
160
* @param {string} jsonToImport - JSON string to import
161
* @param {object} [options] - Import options
162
* @param {boolean} [options.skipDuplicates=false] - Skip duplicate keys if true
163
* @returns {number} New cache size after import
164
*/
165
importJson(jsonToImport, options)
166
```
167
168
### Cache Constructor
169
170
Creates new independent cache instances for isolation and multi-tenancy.
171
172
```javascript { .api }
173
/**
174
* Cache constructor for creating new independent cache instances
175
* @constructor
176
*/
177
function Cache()
178
```
179
180
## Usage Examples
181
182
### Basic Operations
183
184
```javascript
185
const cache = require('memory-cache');
186
187
// Store simple values
188
cache.put('config', { theme: 'dark', lang: 'en' });
189
cache.put('counter', 42);
190
191
// Retrieve values
192
const config = cache.get('config');
193
const counter = cache.get('counter');
194
195
// Check cache size
196
console.log('Cache has', cache.size(), 'entries');
197
198
// List all keys
199
console.log('Keys:', cache.keys());
200
```
201
202
### Expiration and Callbacks
203
204
```javascript
205
const cache = require('memory-cache');
206
207
// Store with 30-second expiration
208
cache.put('session:abc123', { userId: 456, role: 'admin' }, 30000);
209
210
// Store with expiration and cleanup callback
211
cache.put('temp:processing', { status: 'active' }, 5000, function(key, value) {
212
console.log('Processing job', key, 'expired');
213
// Perform cleanup operations
214
});
215
216
// Check if value is still cached
217
setTimeout(() => {
218
const session = cache.get('session:abc123');
219
if (session) {
220
console.log('Session still active');
221
} else {
222
console.log('Session expired');
223
}
224
}, 35000);
225
```
226
227
### Multiple Cache Instances
228
229
```javascript
230
const { Cache } = require('memory-cache');
231
232
// Create separate caches for different purposes
233
const userCache = new Cache();
234
const productCache = new Cache();
235
236
// Each cache operates independently
237
userCache.put('active', ['user1', 'user2']);
238
productCache.put('active', ['prod1', 'prod2']);
239
240
console.log('Users:', userCache.get('active'));
241
console.log('Products:', productCache.get('active'));
242
243
// Enable debugging on specific cache
244
userCache.debug(true);
245
userCache.get('active'); // Counts as hit
246
userCache.get('missing'); // Counts as miss
247
248
console.log('User cache hits:', userCache.hits());
249
console.log('User cache misses:', userCache.misses());
250
```
251
252
### Data Export and Import
253
254
```javascript
255
const cache = require('memory-cache');
256
257
// Populate cache
258
cache.put('user:1', { name: 'Alice' });
259
cache.put('user:2', { name: 'Bob' });
260
cache.put('temp', 'expires soon', 1000);
261
262
// Export cache data
263
const exported = cache.exportJson();
264
console.log('Exported:', exported);
265
266
// Clear cache and import data back
267
cache.clear();
268
const importedSize = cache.importJson(exported);
269
console.log('Imported', importedSize, 'entries');
270
271
// Import with skip duplicates option
272
const moreData = '{"user:3":{"value":{"name":"Charlie"},"expire":"NaN"}}';
273
cache.importJson(moreData, { skipDuplicates: true });
274
```
275
276
## Types
277
278
```javascript { .api }
279
/**
280
* Options object for importJson method
281
* @typedef {object} ImportOptions
282
* @property {boolean} [skipDuplicates=false] - Skip duplicate keys during import
283
*/
284
285
/**
286
* Timeout callback function signature
287
* @callback TimeoutCallback
288
* @param {string} key - The key that expired
289
* @param {*} value - The value that was cached
290
*/
291
```
292
293
## Error Handling
294
295
The cache methods can throw errors in the following situations:
296
297
- `put()` throws `Error` if `time` parameter is not a positive number
298
- `put()` throws `Error` if `timeoutCallback` parameter is not a function
299
- `importJson()` will throw if JSON parsing fails due to invalid JSON format
300
301
```javascript
302
const cache = require('memory-cache');
303
304
try {
305
// This will throw an error
306
cache.put('key', 'value', -100); // Negative time
307
} catch (error) {
308
console.error('Cache error:', error.message);
309
}
310
311
try {
312
// This will throw an error
313
cache.put('key', 'value', 1000, 'not a function');
314
} catch (error) {
315
console.error('Cache error:', error.message);
316
}
317
```