node-cache

Simple and fast NodeJS internal caching. Node internal in memory cache like memcached.

node-cache

Simple and fast NodeJS internal caching.

A simple caching module that has set, get and delete methods and works a little bit like memcached. Keys can have a timeout after which they expire and are cleaned from the cache.
All keys are stored in a single object so the practical limit is at around 1m keys.

Install

  npm install node-cache

Or just require the node_cache.js file to get the superclass

Examples:

var NodeCache = require( "node-cache" );
var myCache = new NodeCache();
  • stdTTL: (default: 0) the standard ttl as number in seconds for every generated cache element.
    0 = unlimited
  • checkperiod: (default: 600) The period in seconds, as a number, used for the automatic delete check interval.
    0 = no periodic check.
    Note: If you use checkperiod > 0 you script will not exit at the end, because a internal timeout will allways be active.
var NodeCache = require( "node-cache" );
var myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );

myCache.set( key, val, [ ttl ], [callback] )

Sets a key value pair. It is possible to define a ttl (in seconds).
Returns true on success.

obj = { my: "Special", variable: 42 };
myCache.set( "myKey", obj, function( errsuccess ){
  if( !err && success ){
    console.log( success );
    // true 
    // ... do something ... 
  }
});

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

obj = { my: "Special", variable: 42 };
success = myCache.set( "myKey", obj, 10000 );
// true 

myCache.get( key, [callback] )

Gets a saved value from the cache. Returns an empty object {} if not found or expired. If the value was found it returns an object with the key value pair.

myCache.get( "myKey", function( errvalue ){
  if( !err ){
    console.log( value );
    // { "myKey": { my: "Special", variable: 42 } } 
    // ... do something ... 
  }
});

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

value = myCache.get( "myKey" );
// { "myKey": { my: "Special", variable: 42 } } 

myCache.get( [ key1, key2, ... ,keyn ], [callback] )

Gets multiple saved values from the cache. Returns an empty object {} if not found or expired. If the value was found it returns an object with the key value pair.

myCache.get( [ "myKeyA", "myKeyB" ], function( errvalue ){
  if( !err ){
    console.log( value );
    /*
      {
        "myKeyA": { my: "Special", variable: 123 },
        "myKeyB": { the: "Glory", answer: 42 }
      }
    */
    // ... do something ... 
  }
});

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

value = myCache.get( [ "myKeyA", "myKeyB" ] );
/*
  {
    "myKeyA": { my: "Special", variable: 123 },
    "myKeyB": { the: "Glory", answer: 42 }
  }
*/

myCache.del( key, [callback] )

Delete a key. Returns the number of deleted entries. A delete will never fail.

myCache.del( "myKey", function( err, count ){
  if( !err ){
    console.log( count ); // 1
    // ... do something ...
  }
});

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

value = myCache.del( "myKeyA" );
// 1 

myCache.del( [ key1, key2, ... ,keyn ], [callback] )

Delete multiple keys. Returns the number of deleted entries. A delete will never fail.

myCache.del( [ "myKeyA", "myKeyB" ], function( errcount ){
  if( !err ){
    console.log( count ); // 2 
    // ... do something ... 
  }
});

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

value = myCache.del( [ "myKeyA", "myKeyB", "notExistendKey" ] );
// 2 

myCache.ttl( key, ttl, [callback] )

Redefine the ttl of a key. Returns true if the key has been found and changed. Otherwise returns false.
If the ttl-argument isn't passed the default-TTL will be used.

myCache = new NodeCache( { stdTTL: 100 } )
myCache.ttl( "existendKey", 100, function( errchanged ){
  if( !err ){
    console.log( changed ); // true 
    // ... do something ... 
  }
});
 
myCache.ttl( "missingKey", 100, function( errchanged ){
  if( !err ){
    console.log( changed ); // false 
    // ... do something ... 
  }
});
 
myCache.ttl( "existendKey", function( errchanged ){
  if( !err ){
    console.log( changed ); // true 
    // ... do something ... 
  }
});

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

value = myCache.ttl( "existendKey", 100 );
// true 

myCache.keys( [callback] )

Returns an array of all existing keys.

// async 
myCache.keys( function( errmykeys ){
  if( !err ){
    console.log( mykeys );
   // [ "all", "my", "keys", "foo", "bar" ] 
  }
});
 
// sync 
mykeys = myCache.keys();
 
console.log( mykeys );
// [ "all", "my", "keys", "foo", "bar" ] 
 

myCache.getStats()

Returns the statistics.

myCache.getStats();
  /*
    {
      keys: 0,    // global key count
      hits: 0,    // global hit count
      misses: 0,  // global miss count
      ksize: 0,   // global key size count
      vsize: 0    // global value size count
    }
  */

myCache.flushAll()

Flush all data.

myCache.flushAll();
myCache.getStats();
  /*
    {
      keys: 0,    // global key count
      hits: 0,    // global hit count
      misses: 0,  // global miss count
      ksize: 0,   // global key size count
      vsize: 0    // global value size count
    }
  */

Events

Fired when a key has been added or changed. You will get the key and the value as callback argument.

myCache.on( "set", function( keyvalue ){
    // ... do something ...   
});

Fired when a key has been removed manually or due to expiry. You will get the key as callback argument.

myCache.on( "del", function( key ){
    // ... do something ...   
});

Fired when a key expires. You will get the key and value as callback argument.

myCache.on( "expired", function( keyvalue ){
    // ... do something ...   
});

Fired when the cache has been flushed.

myCache.on( "flush", function(){
    // ... do something ...   
});
VersionDateDescription
v1.1.02014-11-07added .keys method to list all existing keys
v1.0.32014-11-07fix for setting numeric values. Thanks to kaspars + optimized key ckeck.
v1.0.22014-09-17Small change for better ttl handling
v1.0.12014-05-22Readme typos. Thanks to mjschranz
v1.0.02014-04-09Made callbacks optional. So it's now possible to use a syncron syntax. The old syntax should also work well. Push : Bugfix for the value 0
v0.4.12013-10-02Added the value to expired event
v0.4.02013-10-02Added nodecache events
v0.3.22012-05-31Added Travis tests

NameDescription
rsmqA really simple message queue based on Redis
redis-sessionsAn advanced session store for NodeJS and Redis
connect-redis-sessionsA connect or express middleware to simply use the redis sessions. With redis sessions you can handle multiple sessions per user_id.
redis-heartbeatPulse a heartbeat to redis. This can be used to detach or attach servers to nginx or similar problems.
systemhealthNode module to run simple custom checks for your machine or it's connections. It will use redis-heartbeat to send the current state to redis.
task-queue-workerA powerful tool for background processing of tasks that are run by making standard http requests.
soyerSoyer is small lib for serverside use of Google Closure Templates with node.js.
grunt-soy-compileCompile Goggle Closure Templates ( SOY ) templates inclding the handling of XLIFF language files.
backlunrA solution to bring Backbone Collections together with the browser fulltext search engine Lunr.js

The MIT License (MIT)

Copyright © 2013 Mathias Peter, http://www.tcs.de

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.