UNPKG

20.3 kBMarkdownView Raw
1![Logo](./logo/logo.png)
2
3[![Build Status](https://secure.travis-ci.org/node-cache/node-cache.svg?branch=master)](http://travis-ci.org/node-cache/node-cache)
4[![Windows Tests](https://img.shields.io/appveyor/ci/erdii/node-cache.svg?label=Windows%20Test)](https://ci.appveyor.com/project/erdii/node-cache)
5[![Dependency Status](https://david-dm.org/node-cache/node-cache.svg)](https://david-dm.org/node-cache/node-cache)
6[![NPM version](https://badge.fury.io/js/node-cache.svg)](https://www.npmjs.com/package/node-cache)
7[![NPM package downloads per month](https://img.shields.io/npm/dm/node-cache)](https://www.npmjs.com/package/node-cache)
8[![Coveralls Coverage](https://img.shields.io/coveralls/node-cache/node-cache.svg)](https://coveralls.io/github/node-cache/node-cache)
9
10[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tcs-de/nodecache?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
11
12[![NPM](https://nodei.co/npm/node-cache.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/node-cache/)
13
14# Simple and fast NodeJS internal caching.
15
16A simple caching module that has `set`, `get` and `delete` methods and works a little bit like memcached.
17Keys can have a timeout (`ttl`) after which they expire and are deleted from the cache.
18All keys are stored in a single object so the practical limit is at around 1m keys.
19
20
21## BREAKING MAJOR RELEASE v5.x
22
23The recent 5.x release:
24* dropped support for node versions before 8.x!
25* removed the callback-based api from all methods (you can re-enable them with the option `enableLegacyCallbacks`)
26
27## BREAKING MAJOR RELEASE v6.x UPCOMING
28
29Although not breaking per definition, our typescript rewrite will change internal functions and their names.
30Please get in contact with us, if you are using some parts of node-cache's internal api so we can work something out!
31
32
33# Install
34
35```bash
36 npm install node-cache --save
37```
38
39Or just require the `node_cache.js` file to get the superclass
40
41# Examples:
42
43## Initialize (INIT):
44
45```js
46const NodeCache = require( "node-cache" );
47const myCache = new NodeCache();
48```
49
50### Options
51
52- `stdTTL`: *(default: `0`)* the standard ttl as number in seconds for every generated cache element.
53`0` = unlimited
54- `checkperiod`: *(default: `600`)* The period in seconds, as a number, used for the automatic delete check interval.
55`0` = no periodic check.
56- `useClones`: *(default: `true`)* en/disable cloning of variables. If `true` you'll get a copy of the cached variable. If `false` you'll save and get just the reference.
57**Note:**
58 - `true` is recommended if you want **simplicity**, because it'll behave like a server-based cache (it caches copies of plain data).
59 - `false` is recommended if you want to achieve **performance** or save mutable objects or other complex types with mutability involved and wanted, because it'll only store references of your data.
60 - _Here's a [simple code example](https://runkit.com/mpneuried/useclones-example-83) showing the different behavior_
61- `deleteOnExpire`: *(default: `true`)* whether variables will be deleted automatically when they expire.
62If `true` the variable will be deleted. If `false` the variable will remain. You are encouraged to handle the variable upon the event `expired` by yourself.
63- `enableLegacyCallbacks`: *(default: `false`)* re-enables the usage of callbacks instead of sync functions. Adds an additional `cb` argument to each function which resolves to `(err, result)`. will be removed in node-cache v6.x.
64- `maxKeys`: *(default: `-1`)* specifies a maximum amount of keys that can be stored in the cache. If a new item is set and the cache is full, an error is thrown and the key will not be saved in the cache. -1 disables the key limit.
65
66```js
67const NodeCache = require( "node-cache" );
68const myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );
69```
70
71**Since `4.1.0`**:
72*Key-validation*: The keys can be given as either `string` or `number`, but are casted to a `string` internally anyway.
73All other types will throw an error.
74
75## Store a key (SET):
76
77`myCache.set( key, val, [ ttl ] )`
78
79Sets a `key` `value` pair. It is possible to define a `ttl` (in seconds).
80Returns `true` on success.
81
82```js
83obj = { my: "Special", variable: 42 };
84
85success = myCache.set( "myKey", obj, 10000 );
86// true
87```
88
89> Note: If the key expires based on it's `ttl` it will be deleted entirely from the internal data object.
90
91
92## Store multiple keys (MSET):
93
94`myCache.mset(Array<{key, val, ttl?}>)`
95
96Sets multiple `key` `val` pairs. It is possible to define a `ttl` (seconds).
97Returns `true` on success.
98
99```js
100const obj = { my: "Special", variable: 42 };
101const obj2 = { my: "other special", variable: 1337 };
102
103const success = myCache.mset([
104 {key: "myKey", val: obj, ttl: 10000},
105 {key: "myKey2", val: obj2},
106])
107```
108
109## Retrieve a key (GET):
110
111`myCache.get( key )`
112
113Gets a saved value from the cache.
114Returns a `undefined` if not found or expired.
115If the value was found it returns an object with the `key` `value` pair.
116
117```js
118value = myCache.get( "myKey" );
119if ( value == undefined ){
120 // handle miss!
121}
122// { my: "Special", variable: 42 }
123```
124
125**Since `2.0.0`**:
126
127The return format changed to a simple value and a `ENOTFOUND` error if not found *( as result instance of `Error` )
128
129**Since `2.1.0`**:
130
131The return format changed to a simple value, but a due to discussion in #11 a miss shouldn't return an error.
132So after 2.1.0 a miss returns `undefined`.
133
134## Take a key (TAKE):
135
136`myCache.take( key )`
137
138get the cached value and remove the key from the cache.
139Equivalent to calling `get(key)` + `del(key)`.
140Useful for implementing `single use` mechanism such as OTP, where once a value is read it will become obsolete.
141
142```js
143myCache.set( "myKey", "myValue" )
144myCache.has( "myKey" ) // returns true because the key is cached right now
145value = myCache.take( "myKey" ) // value === "myValue"; this also deletes the key
146myCache.has( "myKey" ) // returns false because the key has been deleted
147```
148
149## Get multiple keys (MGET):
150
151`myCache.mget( [ key1, key2, ..., keyn ] )`
152
153Gets multiple saved values from the cache.
154Returns an empty object `{}` if not found or expired.
155If the value was found it returns an object with the `key` `value` pair.
156
157```js
158value = myCache.mget( [ "myKeyA", "myKeyB" ] );
159/*
160 {
161 "myKeyA": { my: "Special", variable: 123 },
162 "myKeyB": { the: "Glory", answer: 42 }
163 }
164*/
165```
166
167**Since `2.0.0`**:
168
169The method for mget changed from `.get( [ "a", "b" ] )` to `.mget( [ "a", "b" ] )`
170
171## Delete a key (DEL):
172
173`myCache.del( key )`
174
175Delete a key. Returns the number of deleted entries. A delete will never fail.
176
177```js
178value = myCache.del( "A" );
179// 1
180```
181
182## Delete multiple keys (MDEL):
183
184`myCache.del( [ key1, key2, ..., keyn ] )`
185
186Delete multiple keys. Returns the number of deleted entries. A delete will never fail.
187
188```js
189value = myCache.del( "A" );
190// 1
191
192value = myCache.del( [ "B", "C" ] );
193// 2
194
195value = myCache.del( [ "A", "B", "C", "D" ] );
196// 1 - because A, B and C not exists
197```
198
199## Change TTL (TTL):
200
201`myCache.ttl( key, ttl )`
202
203Redefine the ttl of a key. Returns true if the key has been found and changed. Otherwise returns false.
204If the ttl-argument isn't passed the default-TTL will be used.
205
206The key will be deleted when passing in a `ttl < 0`.
207
208```js
209myCache = new NodeCache( { stdTTL: 100 } )
210changed = myCache.ttl( "existentKey", 100 )
211// true
212
213changed2 = myCache.ttl( "missingKey", 100 )
214// false
215
216changed3 = myCache.ttl( "existentKey" )
217// true
218```
219
220## Get TTL (getTTL):
221
222`myCache.getTtl( key )`
223
224Receive the ttl of a key.
225You will get:
226- `undefined` if the key does not exist
227- `0` if this key has no ttl
228- a timestamp in ms representing the time at which the key will expire
229
230```js
231myCache = new NodeCache( { stdTTL: 100 } )
232
233// Date.now() = 1456000500000
234myCache.set( "ttlKey", "MyExpireData" )
235myCache.set( "noTtlKey", "NonExpireData", 0 )
236
237ts = myCache.getTtl( "ttlKey" )
238// ts wil be approximately 1456000600000
239
240ts = myCache.getTtl( "ttlKey" )
241// ts wil be approximately 1456000600000
242
243ts = myCache.getTtl( "noTtlKey" )
244// ts = 0
245
246ts = myCache.getTtl( "unknownKey" )
247// ts = undefined
248```
249
250## List keys (KEYS)
251
252`myCache.keys()`
253
254Returns an array of all existing keys.
255
256```js
257mykeys = myCache.keys();
258
259console.log( mykeys );
260// [ "all", "my", "keys", "foo", "bar" ]
261```
262
263## Has key (HAS)
264
265`myCache.has( key )`
266
267Returns boolean indicating if the key is cached.
268
269```js
270exists = myCache.has( 'myKey' );
271
272console.log( exists );
273```
274
275## Statistics (STATS):
276
277`myCache.getStats()`
278
279Returns the statistics.
280
281```js
282myCache.getStats();
283 /*
284 {
285 keys: 0, // global key count
286 hits: 0, // global hit count
287 misses: 0, // global miss count
288 ksize: 0, // global key size count in approximately bytes
289 vsize: 0 // global value size count in approximately bytes
290 }
291 */
292```
293
294## Flush all data (FLUSH):
295
296`myCache.flushAll()`
297
298Flush all data.
299
300```js
301myCache.flushAll();
302myCache.getStats();
303 /*
304 {
305 keys: 0, // global key count
306 hits: 0, // global hit count
307 misses: 0, // global miss count
308 ksize: 0, // global key size count in approximately bytes
309 vsize: 0 // global value size count in approximately bytes
310 }
311 */
312```
313
314## Flush the stats (FLUSH STATS):
315
316`myCache.flushStats()`
317
318Flush the stats.
319
320```js
321myCache.flushStats();
322myCache.getStats();
323 /*
324 {
325 keys: 0, // global key count
326 hits: 0, // global hit count
327 misses: 0, // global miss count
328 ksize: 0, // global key size count in approximately bytes
329 vsize: 0 // global value size count in approximately bytes
330 }
331 */
332```
333
334## Close the cache:
335
336`myCache.close()`
337
338This will clear the interval timeout which is set on check period option.
339
340```js
341myCache.close();
342```
343
344# Events
345
346## set
347
348Fired when a key has been added or changed.
349You will get the `key` and the `value` as callback argument.
350
351```js
352myCache.on( "set", function( key, value ){
353 // ... do something ...
354});
355```
356
357## del
358
359Fired when a key has been removed manually or due to expiry.
360You will get the `key` and the deleted `value` as callback arguments.
361
362```js
363myCache.on( "del", function( key, value ){
364 // ... do something ...
365});
366```
367
368## expired
369
370Fired when a key expires.
371You will get the `key` and `value` as callback argument.
372
373```js
374myCache.on( "expired", function( key, value ){
375 // ... do something ...
376});
377```
378
379## flush
380
381Fired when the cache has been flushed.
382
383```js
384myCache.on( "flush", function(){
385 // ... do something ...
386});
387```
388
389## flush_stats
390
391Fired when the cache stats has been flushed.
392
393```js
394myCache.on( "flush_stats", function(){
395 // ... do something ...
396});
397```
398
399
400## Breaking changes
401
402### version `2.x`
403
404Due to the [Issue #11](https://github.com/mpneuried/nodecache/issues/11) the return format of the `.get()` method has been changed!
405
406Instead of returning an object with the key `{ "myKey": "myValue" }` it returns the value itself `"myValue"`.
407
408### version `3.x`
409
410Due to the [Issue #30](https://github.com/mpneuried/nodecache/issues/30) and [Issue #27](https://github.com/mpneuried/nodecache/issues/27) variables will now be cloned.
411This could break your code, because for some variable types ( e.g. Promise ) its not possible to clone them.
412You can disable the cloning by setting the option `useClones: false`. In this case it's compatible with version `2.x`.
413
414### version `5.x`
415
416Callbacks are deprecated in this version. They are still useable when enabling the `enableLegacyCallbacks` option when initializing the cache. Callbacks will be completely removed in `6.x`.
417
418## Compatibility
419
420Node-Cache supports all node versions >= 8
421
422## Release History
423|Version|Date|Description|
424|:--:|:--:|:--|
425|5.1.0|2019-12-08|Add .take() from PR [#160] and .flushStats from PR [#161]. Thanks to [Sujesh Thekkepatt](https://github.com/sujeshthekkepatt) and [Gopalakrishna Palem](https://github.com/KrishnaPG)!|
426|5.0.2|2019-11-17|Fixed bug where expired values were deleted even though `deleteOnExpire` was set to `false`. Thanks to [fielding-wilson](https://github.com/fielding-wilson)!|
427|5.0.1|2019-10-31|Fixed bug where users could not set null values. Thanks to [StefanoSega](https://github.com/StefanoSega), [jwest23](https://github.com/jwest23) and [marudor](https://github.com/marudor)!|
428|5.0.0|2019-10-23|Remove lodash dependency, add .has(key) and .mset([{key,val,ttl}]) methods to the cache. Thanks to [Regev Brody](https://github.com/regevbr) for PR [#132] and [Sujesh Thekkepatt](https://github.com/sujeshthekkepatt) for PR [#142]! Also thank you, to all other contributors that remain unnamed here!|
429|4.2.1|2019-07-22|Upgrade lodash to version 4.17.15 to suppress messages about unrelated security vulnerability|
430|4.2.0|2018-02-01|Add options.promiseValueSize for promise value. Thanks to [Ryan Roemer](https://github.com/ryan-roemer) for the pull [#84]; Added option `deleteOnExpire`; Added DefinitelyTyped Typescript definitions. Thanks to [Ulf Seltmann](https://github.com/useltmann) for the pulls [#90] and [#92]; Thanks to [Daniel Jin](https://github.com/danieljin) for the readme fix in pull [#93]; Optimized test and ci configs.|
431|4.1.1|2016-12-21|fix internal check interval for node < 0.10.25, thats the default node for ubuntu 14.04. Thanks to [Jimmy Hwang](https://github.com/JimmyHwang) for the pull [#78](https://github.com/mpneuried/nodecache/pull/78); added more docker tests|
432|4.1.0|2016-09-23|Added tests for different key types; Added key validation (must be `string` or `number`); Fixed `.del` bug where trying to delete a `number` key resulted in no deletion at all.|
433|4.0.0|2016-09-20|Updated tests to mocha; Fixed `.ttl` bug to not delete key on `.ttl( key, 0 )`. This is also relevant if `stdTTL=0`. *This causes the breaking change to `4.0.0`.*|
434|3.2.1|2016-03-21|Updated lodash to 4.x.; optimized grunt |
435|3.2.0|2016-01-29|Added method `getTtl` to get the time when a key expires. See [#49](https://github.com/mpneuried/nodecache/issues/49)|
436|3.1.0|2016-01-29|Added option `errorOnMissing` to throw/callback an error o a miss during a `.get( "key" )`. Thanks to [David Godfrey](https://github.com/david-byng) for the pull [#45](https://github.com/mpneuried/nodecache/pull/45). Added docker files and a script to run test on different node versions locally|
437|3.0.1|2016-01-13|Added `.unref()` to the checkTimeout so until node `0.10` it's not necessary to call `.close()` when your script is done. Thanks to [Doug Moscrop](https://github.com/dougmoscrop) for the pull [#44](https://github.com/mpneuried/nodecache/pull/44).|
438|3.0.0|2015-05-29|Return a cloned version of the cached element and save a cloned version of a variable. This can be disabled by setting the option `useClones:false`. (Thanks for #27 to [cheshirecatalyst](https://github.com/cheshirecatalyst) and for #30 to [Matthieu Sieben](https://github.com/matthieusieben))|
439|~~2.2.0~~|~~2015-05-27~~|REVOKED VERSION, because of conficts. See [Issue #30](https://github.com/mpneuried/nodecache/issues/30). So `2.2.0` is now `3.0.0`|
440|2.1.1|2015-04-17|Passed old value to the `del` event. Thanks to [Qix](https://github.com/qix) for the pull.|
441|2.1.0|2015-04-17|Changed get miss to return `undefined` instead of an error. Thanks to all [#11](https://github.com/mpneuried/nodecache/issues/11) contributors |
442|2.0.1|2015-04-17|Added close function (Thanks to [ownagedj](https://github.com/ownagedj)). Changed the development environment to use grunt.|
443|2.0.0|2015-01-05|changed return format of `.get()` with a error return on a miss and added the `.mget()` method. *Side effect: Performance of .get() up to 330 times faster!*|
444|1.1.0|2015-01-05|added `.keys()` method to list all existing keys|
445|1.0.3|2014-11-07|fix for setting numeric values. Thanks to [kaspars](https://github.com/kaspars) + optimized key ckeck.|
446|1.0.2|2014-09-17|Small change for better ttl handling|
447|1.0.1|2014-05-22|Readme typos. Thanks to [mjschranz](https://github.com/mjschranz)|
448|1.0.0|2014-04-09|Made `callback`s optional. So it's now possible to use a syncron syntax. The old syntax should also work well. Push : Bugfix for the value `0`|
449|0.4.1|2013-10-02|Added the value to `expired` event|
450|0.4.0|2013-10-02|Added nodecache events|
451|0.3.2|2012-05-31|Added Travis tests|
452
453[![NPM](https://nodei.co/npm-dl/node-cache.png?months=6)](https://nodei.co/npm/node-cache/)
454
455## Other projects
456
457|Name|Description|
458|:--|:--|
459|[**rsmq**](https://github.com/smrchy/rsmq)|A really simple message queue based on redis|
460|[**redis-heartbeat**](https://github.com/mpneuried/redis-heartbeat)|Pulse a heartbeat to redis. This can be used to detach or attach servers to nginx or similar problems.|
461|[**systemhealth**](https://github.com/mpneuried/systemhealth)|Node module to run simple custom checks for your machine or it's connections. It will use [redis-heartbeat](https://github.com/mpneuried/redis-heartbeat) to send the current state to redis.|
462|[**rsmq-cli**](https://github.com/mpneuried/rsmq-cli)|a terminal client for rsmq|
463|[**rest-rsmq**](https://github.com/smrchy/rest-rsmq)|REST interface for.|
464|[**redis-sessions**](https://github.com/smrchy/redis-sessions)|An advanced session store for NodeJS and Redis|
465|[**connect-redis-sessions**](https://github.com/mpneuried/connect-redis-sessions)|A connect or express middleware to simply use the [redis sessions](https://github.com/smrchy/redis-sessions). With [redis sessions](https://github.com/smrchy/redis-sessions) you can handle multiple sessions per user_id.|
466|[**redis-notifications**](https://github.com/mpneuried/redis-notifications)|A redis based notification engine. It implements the rsmq-worker to safely create notifications and recurring reports.|
467|[**nsq-logger**](https://github.com/mpneuried/nsq-logger)|Nsq service to read messages from all topics listed within a list of nsqlookupd services.|
468|[**nsq-topics**](https://github.com/mpneuried/nsq-topics)|Nsq helper to poll a nsqlookupd service for all it's topics and mirror it locally.|
469|[**nsq-nodes**](https://github.com/mpneuried/nsq-nodes)|Nsq helper to poll a nsqlookupd service for all it's nodes and mirror it locally.|
470|[**nsq-watch**](https://github.com/mpneuried/nsq-watch)|Watch one or many topics for unprocessed messages.|
471|[**hyperrequest**](https://github.com/mpneuried/hyperrequest)|A wrapper around [hyperquest](https://github.com/substack/hyperquest) to handle the results|
472|[**task-queue-worker**](https://github.com/smrchy/task-queue-worker)|A powerful tool for background processing of tasks that are run by making standard http requests
473|[**soyer**](https://github.com/mpneuried/soyer)|Soyer is small lib for server side use of Google Closure Templates with node.js.|
474|[**grunt-soy-compile**](https://github.com/mpneuried/grunt-soy-compile)|Compile Goggle Closure Templates ( SOY ) templates including the handling of XLIFF language files.|
475|[**backlunr**](https://github.com/mpneuried/backlunr)|A solution to bring Backbone Collections together with the browser fulltext search engine Lunr.js|
476|[**domel**](https://github.com/mpneuried/domel)|A simple dom helper if you want to get rid of jQuery|
477|[**obj-schema**](https://github.com/mpneuried/obj-schema)|Simple module to validate an object by a predefined schema|
478
479# The MIT License (MIT)
480
481Copyright © 2019 Mathias Peter and the node-cache maintainers, https://github.com/node-cache/node-cache
482
483Permission is hereby granted, free of charge, to any person obtaining
484a copy of this software and associated documentation files (the
485'Software'), to deal in the Software without restriction, including
486without limitation the rights to use, copy, modify, merge, publish,
487distribute, sublicense, and/or sell copies of the Software, and to
488permit persons to whom the Software is furnished to do so, subject to
489the following conditions:
490
491The above copyright notice and this permission notice shall be
492included in all copies or substantial portions of the Software.
493
494THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
495EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
496MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
497IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
498CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
499TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
500SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
501
\No newline at end of file