UNPKG

20.8 kBMarkdownView Raw
1node-cache
2===========
3
4[![Build Status](https://secure.travis-ci.org/mpneuried/nodecache.svg?branch=master)](http://travis-ci.org/mpneuried/nodecache)
5[![Windows Tests](https://img.shields.io/appveyor/ci/mpneuried/nodecache.svg?label=Windows%20Test)](https://ci.appveyor.com/project/mpneuried/nodecache)
6[![Dependency Status](https://david-dm.org/mpneuried/nodecache.svg)](https://david-dm.org/mpneuried/nodecache)
7[![NPM version](https://badge.fury.io/js/node-cache.svg)](http://badge.fury.io/js/node-cache)
8[![Coveralls Coverage](https://img.shields.io/coveralls/mpneuried/nodecache.svg)](https://coveralls.io/github/mpneuried/nodecache)
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**Since `4.1.0`**:
21*Key-validation*: The keys can be given as either `string` or `number`, but are casted to a `string` internally anyway.
22All other types will either throw an error or call the callback with an error.
23
24
25# Install
26
27```bash
28 npm install node-cache --save
29```
30
31Or just require the `node_cache.js` file to get the superclass
32
33# Examples:
34
35## Initialize (INIT):
36
37```js
38const NodeCache = require( "node-cache" );
39const myCache = new NodeCache();
40```
41
42### Options
43
44- `stdTTL`: *(default: `0`)* the standard ttl as number in seconds for every generated cache element.
45`0` = unlimited
46- `checkperiod`: *(default: `600`)* The period in seconds, as a number, used for the automatic delete check interval.
47`0` = no periodic check.
48- `errorOnMissing`: *(default: `false`)* en/disable throwing or passing an error to the callback if attempting to `.get` a missing or expired value.
49- `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.
50**Note:** `true` is recommended, because it'll behave like a server-based caching. You should set `false` if you want to save mutable objects or other complex types with mutability involved and wanted.
51_Here's a [simple code exmaple](https://runkit.com/mpneuried/useclones-example-83) showing the different behavior_
52- `deleteOnExpire`: *(default: `true`)* whether variables will be deleted automatically when they expire.
53If `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.
54
55```js
56const NodeCache = require( "node-cache" );
57const myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );
58```
59
60## Store a key (SET):
61
62`myCache.set( key, val, [ ttl ], [callback] )`
63
64Sets a `key` `value` pair. It is possible to define a `ttl` (in seconds).
65Returns `true` on success.
66
67```js
68obj = { my: "Special", variable: 42 };
69myCache.set( "myKey", obj, function( err, success ){
70 if( !err && success ){
71 console.log( success );
72 // true
73 // ... do something ...
74 }
75});
76```
77
78> Note: If the key expires based on it's `ttl` it will be deleted entirely from the internal data object.
79
80**Since `1.0.0`**:
81Callback is now optional. You can also use synchronous syntax.
82
83```js
84obj = { my: "Special", variable: 42 };
85success = myCache.set( "myKey", obj, 10000 );
86// true
87```
88
89
90## Retrieve a key (GET):
91
92`myCache.get( key, [callback] )`
93
94Gets a saved value from the cache.
95Returns a `undefined` if not found or expired.
96If the value was found it returns an object with the `key` `value` pair.
97
98```js
99myCache.get( "myKey", function( err, value ){
100 if( !err ){
101 if(value == undefined){
102 // key not found
103 }else{
104 console.log( value );
105 //{ my: "Special", variable: 42 }
106 // ... do something ...
107 }
108 }
109});
110```
111
112**Since `1.0.0`**:
113Callback is now optional. You can also use synchronous syntax.
114
115```js
116value = myCache.get( "myKey" );
117if ( value == undefined ){
118 // handle miss!
119}
120// { my: "Special", variable: 42 }
121```
122
123**Since `2.0.0`**:
124
125The return format changed to a simple value and a `ENOTFOUND` error if not found *( as `callback( err )` or on sync call as result instance of `Error` )*.
126
127**Since `2.1.0`**:
128
129The return format changed to a simple value, but a due to discussion in #11 a miss shouldn't return an error.
130So after 2.1.0 a miss returns `undefined`.
131
132**Since `3.1.0`**
133`errorOnMissing` option added
134
135```js
136try{
137 value = myCache.get( "not-existing-key", true );
138} catch( err ){
139 // ENOTFOUND: Key `not-existing-key` not found
140}
141```
142
143## Get multiple keys (MGET):
144
145`myCache.mget( [ key1, key2, ... ,keyn ], [callback] )`
146
147Gets multiple saved values from the cache.
148Returns an empty object `{}` if not found or expired.
149If the value was found it returns an object with the `key` `value` pair.
150
151```js
152myCache.mget( [ "myKeyA", "myKeyB" ], function( err, value ){
153 if( !err ){
154 console.log( value );
155 /*
156 {
157 "myKeyA": { my: "Special", variable: 123 },
158 "myKeyB": { the: "Glory", answer: 42 }
159 }
160 */
161 // ... do something ...
162 }
163});
164```
165
166**Since `1.0.0`**:
167Callback is now optional. You can also use synchronous syntax.
168
169```js
170value = myCache.mget( [ "myKeyA", "myKeyB" ] );
171/*
172 {
173 "myKeyA": { my: "Special", variable: 123 },
174 "myKeyB": { the: "Glory", answer: 42 }
175 }
176*/
177```
178
179**Since `2.0.0`**:
180
181The method for mget changed from `.get( [ "a", "b" ] )` to `.mget( [ "a", "b" ] )`
182
183## Delete a key (DEL):
184
185`myCache.del( key, [callback] )`
186
187Delete a key. Returns the number of deleted entries. A delete will never fail.
188
189```js
190myCache.del( "myKey", function( err, count ){
191 if( !err ){
192 console.log( count ); // 1
193 // ... do something ...
194 }
195});
196```
197
198**Since `1.0.0`**:
199Callback is now optional. You can also use synchronous syntax.
200
201```js
202value = myCache.del( "A" );
203// 1
204```
205
206## Delete multiple keys (MDEL):
207
208`myCache.del( [ key1, key2, ... ,keyn ], [callback] )`
209
210Delete multiple keys. Returns the number of deleted entries. A delete will never fail.
211
212```js
213myCache.del( [ "myKeyA", "myKeyB" ], function( err, count ){
214 if( !err ){
215 console.log( count ); // 2
216 // ... do something ...
217 }
218});
219```
220
221**Since `1.0.0`**:
222Callback is now optional. You can also use synchronous syntax.
223
224```js
225value = myCache.del( "A" );
226// 1
227
228value = myCache.del( [ "B", "C" ] );
229// 2
230
231value = myCache.del( [ "A", "B", "C", "D" ] );
232// 1 - because A, B and C not exists
233```
234
235## Change TTL (TTL):
236
237`myCache.ttl( key, ttl, [callback] )`
238
239Redefine the ttl of a key. Returns true if the key has been found and changed. Otherwise returns false.
240If the ttl-argument isn't passed the default-TTL will be used.
241
242The key will be deleted when passing in a `ttl < 0`.
243
244```js
245myCache = new NodeCache( { stdTTL: 100 } )
246myCache.ttl( "existendKey", 100, function( err, changed ){
247 if( !err ){
248 console.log( changed ); // true
249 // ... do something ...
250 }
251});
252
253myCache.ttl( "missingKey", 100, function( err, changed ){
254 if( !err ){
255 console.log( changed ); // false
256 // ... do something ...
257 }
258});
259
260myCache.ttl( "existendKey", function( err, changed ){
261 if( !err ){
262 console.log( changed ); // true
263 // ... do something ...
264 }
265});
266```
267
268## Get TTL (getTTL):
269
270`myCache.getTtl( key, [callback] )`
271
272Receive the ttl of a key.
273You will get:
274- `undefined` if the key does not exist
275- `0` if this key has no ttl
276- a timestamp in ms until the key expires
277
278```js
279myCache = new NodeCache( { stdTTL: 100 } )
280
281// Date.now() = 1456000500000
282myCache.set( "ttlKey", "MyExpireData" )
283myCache.set( "noTtlKey", "NonExpireData", 0 )
284
285ts = myCache.getTtl( "ttlKey" )
286// ts wil be approximately 1456000600000
287
288myCache.getTtl( "ttlKey", function( err, ts ){
289 if( !err ){
290 // ts wil be approximately 1456000600000
291 }
292});
293// ts wil be approximately 1456000600000
294
295ts = myCache.getTtl( "noTtlKey" )
296// ts = 0
297
298ts = myCache.getTtl( "unknownKey" )
299// ts = undefined
300
301```
302
303## List keys (KEYS)
304
305`myCache.keys( [callback] )`
306
307Returns an array of all existing keys.
308
309```js
310// async
311myCache.keys( function( err, mykeys ){
312 if( !err ){
313 console.log( mykeys );
314 // [ "all", "my", "keys", "foo", "bar" ]
315 }
316});
317
318// sync
319mykeys = myCache.keys();
320
321console.log( mykeys );
322// [ "all", "my", "keys", "foo", "bar" ]
323
324```
325
326## Statistics (STATS):
327
328`myCache.getStats()`
329
330Returns the statistics.
331
332```js
333myCache.getStats();
334 /*
335 {
336 keys: 0, // global key count
337 hits: 0, // global hit count
338 misses: 0, // global miss count
339 ksize: 0, // global key size count
340 vsize: 0 // global value size count
341 }
342 */
343```
344
345## Flush all data (FLUSH):
346
347`myCache.flushAll()`
348
349Flush all data.
350
351```js
352myCache.flushAll();
353myCache.getStats();
354 /*
355 {
356 keys: 0, // global key count
357 hits: 0, // global hit count
358 misses: 0, // global miss count
359 ksize: 0, // global key size count
360 vsize: 0 // global value size count
361 }
362 */
363```
364
365## Close the cache:
366
367`myCache.close()`
368
369This will clear the interval timeout which is set on check period option.
370
371```js
372myCache.close();
373```
374
375# Events
376
377## set
378
379Fired when a key has been added or changed.
380You will get the `key` and the `value` as callback argument.
381
382```js
383myCache.on( "set", function( key, value ){
384 // ... do something ...
385});
386```
387
388## del
389
390Fired when a key has been removed manually or due to expiry.
391You will get the `key` and the deleted `value` as callback arguments.
392
393```js
394myCache.on( "del", function( key, value ){
395 // ... do something ...
396});
397```
398
399## expired
400
401Fired when a key expires.
402You will get the `key` and `value` as callback argument.
403
404```js
405myCache.on( "expired", function( key, value ){
406 // ... do something ...
407});
408```
409
410## flush
411
412Fired when the cache has been flushed.
413
414```js
415myCache.on( "flush", function(){
416 // ... do something ...
417});
418```
419
420
421## Breaking changes
422
423### version `2.x`
424
425Due to the [Issue #11](https://github.com/mpneuried/nodecache/issues/11) the return format of the `.get()` method has been changed!
426
427Instead of returning an object with the key `{ "myKey": "myValue" }` it returns the value itself `"myValue"`.
428
429### version `3.x`
430
431Due 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.
432This could break your code, because for some variable types ( e.g. Promise ) its not possible to clone them.
433You can disable the cloning by setting the option `useClones: false`. In this case it's compatible with version `2.x`.
434
435## Benchmarks
436
437### Version 1.1.x
438
439After adding io.js to the travis test here are the benchmark results for set and get of 100000 elements.
440But be careful with this results, because it has been executed on travis machines, so it is not guaranteed, that it was executed on similar hardware.
441
442**node.js `0.10.36`**
443SET: `324`ms ( `3.24`µs per item )
444GET: `7956`ms ( `79.56`µs per item )
445
446**node.js `0.12.0`**
447SET: `432`ms ( `4.32`µs per item )
448GET: `42767`ms ( `427.67`µs per item )
449
450**io.js `v1.1.0`**
451SET: `510`ms ( `5.1`µs per item )
452GET: `1535`ms ( `15.35`µs per item )
453
454### Version 2.0.x
455
456Again the same benchmarks by travis with version 2.0
457
458**node.js `0.6.21`**
459SET: `786`ms ( `7.86`µs per item )
460GET: `56`ms ( `0.56`µs per item )
461
462**node.js `0.10.36`**
463SET: `353`ms ( `3.53`µs per item )
464GET: `41`ms ( `0.41`µs per item )
465
466**node.js `0.12.2`**
467SET: `327`ms ( `3.27`µs per item )
468GET: `32`ms ( `0.32`µs per item )
469
470**io.js `v1.7.1`**
471SET: `238`ms ( `2.38`µs per item )
472GET: `34`ms ( `0.34`µs per item )
473
474> As you can see the version 2.x will increase the GET performance up to 200x in node 0.10.x.
475This is possible because the memory allocation for the object returned by 1.x is very expensive.
476
477### Version 3.0.x
478
479*see [travis results](https://travis-ci.org/mpneuried/nodecache/builds/64560503)*
480
481**node.js `0.6.21`**
482SET: `786`ms ( `7.24`µs per item )
483GET: `56`ms ( `1.14`µs per item )
484
485**node.js `0.10.38`**
486SET: `353`ms ( `5.41`µs per item )
487GET: `41`ms ( `1.23`µs per item )
488
489**node.js `0.12.4`**
490SET: `327`ms ( `4.63`µs per item )
491GET: `32`ms ( `0.60`µs per item )
492
493**io.js `v2.1.0`**
494SET: `238`ms ( `4.06`µs per item )
495GET: `34`ms ( `0.67`µs per item )
496
497> until the version 3.0.x the object cloning is included, so we lost a little bit of the performance
498
499### Version 3.1.x
500
501**node.js `v0.10.41`**
502SET: `305ms` ( `3.05µs` per item )
503GET: `104ms` ( `1.04µs` per item )
504
505**node.js `v0.12.9`**
506SET: `337ms` ( `3.37µs` per item )
507GET: `167ms` ( `1.67µs` per item )
508
509**node.js `v4.2.6`**
510SET: `356ms` ( `3.56µs` per item )
511GET: `83ms` ( `0.83µs` per item )
512
513## Compatibility
514
515This module should work well back until node `0.6.x`.
516But it's only tested until version `0.10.x` because the build dependencies are not installable ;-) .
517
518## Release History
519|Version|Date|Description|
520|:--:|:--:|:--|
521|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.|
522|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|
523|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.|
524|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`.*|
525|3.2.1|2016-03-21|Updated lodash to 4.x.; optimized grunt |
526|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)|
527|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|
528|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).|
529|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))|
530|~~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`|
531|2.1.1|2015-04-17|Passed old value to the `del` event. Thanks to [Qix](https://github.com/qix) for the pull.|
532|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 |
533|2.0.1|2015-04-17|Added close function (Thanks to [ownagedj](https://github.com/ownagedj)). Changed the development environment to use grunt.|
534|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!*|
535|1.1.0|2015-01-05|added `.keys()` method to list all existing keys|
536|1.0.3|2014-11-07|fix for setting numeric values. Thanks to [kaspars](https://github.com/kaspars) + optimized key ckeck.|
537|1.0.2|2014-09-17|Small change for better ttl handling|
538|1.0.1|2014-05-22|Readme typos. Thanks to [mjschranz](https://github.com/mjschranz)|
539|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`|
540|0.4.1|2013-10-02|Added the value to `expired` event|
541|0.4.0|2013-10-02|Added nodecache events|
542|0.3.2|2012-05-31|Added Travis tests|
543
544[![NPM](https://nodei.co/npm-dl/node-cache.png?months=6)](https://nodei.co/npm/node-cache/)
545
546## Other projects
547
548|Name|Description|
549|:--|:--|
550|[**rsmq**](https://github.com/smrchy/rsmq)|A really simple message queue based on redis|
551|[**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.|
552|[**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.|
553|[**rsmq-cli**](https://github.com/mpneuried/rsmq-cli)|a terminal client for rsmq|
554|[**rest-rsmq**](https://github.com/smrchy/rest-rsmq)|REST interface for.|
555|[**redis-sessions**](https://github.com/smrchy/redis-sessions)|An advanced session store for NodeJS and Redis|
556|[**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.|
557|[**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.|
558|[**nsq-logger**](https://github.com/mpneuried/nsq-logger)|Nsq service to read messages from all topics listed within a list of nsqlookupd services.|
559|[**nsq-topics**](https://github.com/mpneuried/nsq-topics)|Nsq helper to poll a nsqlookupd service for all it's topics and mirror it locally.|
560|[**nsq-nodes**](https://github.com/mpneuried/nsq-nodes)|Nsq helper to poll a nsqlookupd service for all it's nodes and mirror it locally.|
561|[**nsq-watch**](https://github.com/mpneuried/nsq-watch)|Watch one or many topics for unprocessed messages.|
562|[**hyperrequest**](https://github.com/mpneuried/hyperrequest)|A wrapper around [hyperquest](https://github.com/substack/hyperquest) to handle the results|
563|[**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
564|[**soyer**](https://github.com/mpneuried/soyer)|Soyer is small lib for server side use of Google Closure Templates with node.js.|
565|[**grunt-soy-compile**](https://github.com/mpneuried/grunt-soy-compile)|Compile Goggle Closure Templates ( SOY ) templates including the handling of XLIFF language files.|
566|[**backlunr**](https://github.com/mpneuried/backlunr)|A solution to bring Backbone Collections together with the browser fulltext search engine Lunr.js|
567|[**domel**](https://github.com/mpneuried/domel)|A simple dom helper if you want to get rid of jQuery|
568|[**obj-schema**](https://github.com/mpneuried/obj-schema)|Simple module to validate an object by a predefined schema|
569
570# The MIT License (MIT)
571
572Copyright © 2013 Mathias Peter, http://www.tcs.de
573
574Permission is hereby granted, free of charge, to any person obtaining
575a copy of this software and associated documentation files (the
576'Software'), to deal in the Software without restriction, including
577without limitation the rights to use, copy, modify, merge, publish,
578distribute, sublicense, and/or sell copies of the Software, and to
579permit persons to whom the Software is furnished to do so, subject to
580the following conditions:
581
582The above copyright notice and this permission notice shall be
583included in all copies or substantial portions of the Software.
584
585THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
586EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
587MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
588IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
589CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
590TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
591SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
592
\No newline at end of file