UNPKG

10.5 kBMarkdownView Raw
1node-cache
2===========
3
4[![Build Status](https://secure.travis-ci.org/tcs-de/nodecache.png?branch=master)](http://travis-ci.org/tcs-de/nodecache)
5[![Build Status](https://david-dm.org/tcs-de/nodecache.png)](https://david-dm.org/tcs-de/nodecache)
6[![NPM version](https://badge.fury.io/js/node-cache.png)](http://badge.fury.io/js/node-cache)
7
8[![NPM](https://nodei.co/npm/node-cache.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/node-cache/)
9
10# Simple and fast NodeJS internal caching.
11
12A simple caching module that has `set`, `get` and `delete` methods and works a little bit like memcached.
13Keys can have a timeout after which they expire and are cleaned from the cache.
14All keys are stored in a single object so the practical limit is at around 1m keys.
15
16# Install
17
18```bash
19 npm install node-cache
20```
21
22Or just require the `node_cache.js` file to get the superclass
23
24# Examples:
25
26## Initialize (INIT):
27
28```js
29var NodeCache = require( "node-cache" );
30var myCache = new NodeCache();
31```
32
33### Options
34
35- `stdTTL`: *(default: `0`)* the standard ttl as number in seconds for every generated cache element.
36`0` = unlimited
37- `checkperiod`: *(default: `600`)* The period in seconds, as a number, used for the automatic delete check interval.
38`0` = no periodic check.
39**Note:** If you use `checkperiod > 0` you script will not exit at the end, because a internal timeout will allways be active.
40
41```js
42var NodeCache = require( "node-cache" );
43var myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );
44```
45
46## Store a key (SET):
47
48`myCache.set( key, val, [ ttl ], [callback] )`
49
50Sets a `key` `value` pair. It is possible to define a `ttl` (in seconds).
51Returns `true` on success.
52
53```js
54obj = { my: "Special", variable: 42 };
55myCache.set( "myKey", obj, function( err, success ){
56 if( !err && success ){
57 console.log( success );
58 // true
59 // ... do something ...
60 }
61});
62```
63
64**Since `1.0.0`**:
65Callback is now optional. You can also use synchronous syntax.
66
67```js
68obj = { my: "Special", variable: 42 };
69success = myCache.set( "myKey", obj, 10000 );
70// true
71```
72
73
74## Retrieve a key (GET):
75
76`myCache.get( key, [callback] )`
77
78Gets a saved value from the cache.
79Returns an empty object `{}` if not found or expired.
80If the value was found it returns an object with the `key` `value` pair.
81
82```js
83myCache.get( "myKey", function( err, value ){
84 if( !err ){
85 console.log( value );
86 // { "myKey": { my: "Special", variable: 42 } }
87 // ... do something ...
88 }
89});
90```
91
92**Since `1.0.0`**:
93Callback is now optional. You can also use synchronous syntax.
94
95```js
96value = myCache.get( "myKey" );
97// { "myKey": { my: "Special", variable: 42 } }
98```
99
100## Get multiple keys (MGET):
101
102`myCache.get( [ key1, key2, ... ,keyn ], [callback] )`
103
104Gets multiple saved values from the cache.
105Returns an empty object `{}` if not found or expired.
106If the value was found it returns an object with the `key` `value` pair.
107
108```js
109myCache.get( [ "myKeyA", "myKeyB" ], function( err, value ){
110 if( !err ){
111 console.log( value );
112 /*
113 {
114 "myKeyA": { my: "Special", variable: 123 },
115 "myKeyB": { the: "Glory", answer: 42 }
116 }
117 */
118 // ... do something ...
119 }
120});
121```
122
123**Since `1.0.0`**:
124Callback is now optional. You can also use synchronous syntax.
125
126```js
127value = myCache.get( [ "myKeyA", "myKeyB" ] );
128/*
129 {
130 "myKeyA": { my: "Special", variable: 123 },
131 "myKeyB": { the: "Glory", answer: 42 }
132 }
133*/
134```
135
136## Delete a key (DEL):
137
138`myCache.del( key, [callback] )`
139
140Delete a key. Returns the number of deleted entries. A delete will never fail.
141
142```
143myCache.del( "myKey", function( err, count ){
144 if( !err ){
145 console.log( count ); // 1
146 // ... do something ...
147 }
148});
149```
150
151**Since `1.0.0`**:
152Callback is now optional. You can also use synchronous syntax.
153
154```js
155value = myCache.del( "myKeyA" );
156// 1
157```
158
159## Delete multiple keys (MDEL):
160
161`myCache.del( [ key1, key2, ... ,keyn ], [callback] )`
162
163Delete multiple keys. Returns the number of deleted entries. A delete will never fail.
164
165```js
166myCache.del( [ "myKeyA", "myKeyB" ], function( err, count ){
167 if( !err ){
168 console.log( count ); // 2
169 // ... do something ...
170 }
171});
172```
173
174**Since `1.0.0`**:
175Callback is now optional. You can also use synchronous syntax.
176
177```js
178value = myCache.del( [ "myKeyA", "myKeyB", "notExistendKey" ] );
179// 2
180```
181
182## Change TTL (TTL):
183
184`myCache.ttl( key, ttl, [callback] )`
185
186Redefine the ttl of a key. Returns true if the key has been found and changed. Otherwise returns false.
187If the ttl-argument isn't passed the default-TTL will be used.
188
189```js
190myCache = new NodeCache( { stdTTL: 100 } )
191myCache.ttl( "existendKey", 100, function( err, changed ){
192 if( !err ){
193 console.log( changed ); // true
194 // ... do something ...
195 }
196});
197
198myCache.ttl( "missingKey", 100, function( err, changed ){
199 if( !err ){
200 console.log( changed ); // false
201 // ... do something ...
202 }
203});
204
205myCache.ttl( "existendKey", function( err, changed ){
206 if( !err ){
207 console.log( changed ); // true
208 // ... do something ...
209 }
210});
211```
212
213**Since `1.0.0`**:
214Callback is now optional. You can also use synchronous syntax.
215
216```js
217value = myCache.ttl( "existendKey", 100 );
218// true
219```
220
221## List keys (KEYS)
222
223`myCache.keys( [callback] )`
224
225Returns an array of all existing keys.
226
227```js
228// async
229myCache.keys( function( err, mykeys ){
230 if( !err ){
231 console.log( mykeys );
232 // [ "all", "my", "keys", "foo", "bar" ]
233 }
234});
235
236// sync
237mykeys = myCache.keys();
238
239console.log( mykeys );
240// [ "all", "my", "keys", "foo", "bar" ]
241
242```
243
244## Statistics (STATS):
245
246`myCache.getStats()`
247
248Returns the statistics.
249
250```js
251myCache.getStats();
252 /*
253 {
254 keys: 0, // global key count
255 hits: 0, // global hit count
256 misses: 0, // global miss count
257 ksize: 0, // global key size count
258 vsize: 0 // global value size count
259 }
260 */
261```
262
263## Flush all data (FLUSH):
264
265`myCache.flushAll()`
266
267Flush all data.
268
269```js
270myCache.flushAll();
271myCache.getStats();
272 /*
273 {
274 keys: 0, // global key count
275 hits: 0, // global hit count
276 misses: 0, // global miss count
277 ksize: 0, // global key size count
278 vsize: 0 // global value size count
279 }
280 */
281```
282
283# Events
284
285## set
286
287Fired when a key has been added or changed.
288You will get the `key` and the `value` as callback argument.
289
290```js
291myCache.on( "set", function( key, value ){
292 // ... do something ...
293});
294```
295
296## del
297
298Fired when a key has been removed manually or due to expiry.
299You will get the `key` as callback argument.
300
301```js
302myCache.on( "del", function( key ){
303 // ... do something ...
304});
305```
306
307## expired
308
309Fired when a key expires.
310You will get the `key` and `value` as callback argument.
311
312```js
313myCache.on( "expired", function( key, value ){
314 // ... do something ...
315});
316```
317
318## flush
319
320Fired when the cache has been flushed.
321
322```js
323myCache.on( "flush", function(){
324 // ... do something ...
325});
326```
327
328## Release History
329|Version|Date|Description|
330|:--:|:--:|:--|
331|v1.1.0|2014-11-07|added `.keys` method to list all existing keys|
332|v1.0.3|2014-11-07|fix for setting numeric values. Thanks to [kaspars](https://github.com/kaspars) + optimized key ckeck.|
333|v1.0.2|2014-09-17|Small change for better ttl handling|
334|v1.0.1|2014-05-22|Readme typos. Thanks to [mjschranz](https://github.com/mjschranz)|
335|v1.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`|
336|v0.4.1|2013-10-02|Added the value to `expired` event|
337|v0.4.0|2013-10-02|Added nodecache events|
338|v0.3.2|2012-05-31|Added Travis tests|
339
340[![NPM](https://nodei.co/npm-dl/node-cache.png?months=6)](https://nodei.co/npm/node-cache/)
341
342## Other projects
343
344|Name|Description|
345|:--|:--|
346|[**rsmq**](https://github.com/smrchy/rsmq)|A really simple message queue based on Redis|
347|[**redis-sessions**](https://github.com/smrchy/redis-sessions)|An advanced session store for NodeJS and Redis|
348|[**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.|
349|[**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.|
350|[**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.|
351|[**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.|
352|[**soyer**](https://github.com/mpneuried/soyer)|Soyer is small lib for serverside use of Google Closure Templates with node.js.|
353|[**grunt-soy-compile**](https://github.com/mpneuried/grunt-soy-compile)|Compile Goggle Closure Templates ( SOY ) templates inclding the handling of XLIFF language files.|
354|[**backlunr**](https://github.com/mpneuried/backlunr)|A solution to bring Backbone Collections together with the browser fulltext search engine Lunr.js|
355
356
357# The MIT License (MIT)
358
359Copyright © 2013 Mathias Peter, http://www.tcs.de
360
361Permission is hereby granted, free of charge, to any person obtaining
362a copy of this software and associated documentation files (the
363'Software'), to deal in the Software without restriction, including
364without limitation the rights to use, copy, modify, merge, publish,
365distribute, sublicense, and/or sell copies of the Software, and to
366permit persons to whom the Software is furnished to do so, subject to
367the following conditions:
368
369The above copyright notice and this permission notice shall be
370included in all copies or substantial portions of the Software.
371
372THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
373EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
374MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
375IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
376CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
377TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
378SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.