A simple caching module that has set, get and delete methods and works a little bit like memcached.
Keys can have a timeout (ttl) after which they expire and are deleted from the cache.
All keys are stored in a single object so the practical limit is at around 1m keys.
According to the Declaration to not sell out from the original repository, the node-cache package is no longer supported and the authors understandably do not plan to give the repository to other hands, they also recommended that anyone who wants to continue working on the project should create a fork, which is the reason why this project was created.
This project is an important part of our products, but since it is unsupported it is slowly becoming obsolete and requires support and regular maintenance, so it was decided to provide this project with ongoing support.
See CHANGELOG.md for breaking changes, release history, and migration guides.
npm install node-internal-cache --saveconst NodeCache = require( "node-internal-cache" );
const myCache = new NodeCache();stdTTL: (default:0) the standard ttl as number in seconds for every generated cache element.0= unlimitedcheckperiod: (default:600) The period in seconds, as a number, used for the automatic delete check interval.0= no periodic check.useClones: (default:true) en/disable cloning of variables. Iftrueyou'll get a copy of the cached variable. Iffalseyou'll save and get just the reference.
Note:trueis recommended if you want simplicity, because it'll behave like a server-based cache (it caches copies of plain data).falseis 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.- Here's a simple code example showing the different behavior
deleteOnExpire: (default:true) whether variables will be deleted automatically when they expire. Iftruethe variable will be deleted. Iffalsethe variable will remain. You are encouraged to handle the variable upon the eventexpiredby yourself.enableLegacyCallbacks: (default:false) re-enables the usage of callbacks instead of sync functions. Adds an additionalcbargument to each function which resolves to(err, result). will be removed in node-internal-cache v6.x.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.
const NodeCache = require( "node-internal-cache" );
const myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );Since 4.1.0:
Key-validation: The keys can be given as either string or number, but are casted to a string internally anyway.
All other types will throw an error.
myCache.set( key, val, [ ttl ] )
Sets a key value pair. It is possible to define a ttl (in seconds).
Returns true on success.
obj = { my: "Special", variable: 42 };
success = myCache.set( "myKey", obj, 10000 );
// trueNote: If the key expires based on it's
ttlit will be deleted entirely from the internal data object.
myCache.mset(Array<{key, val, ttl?}>)
Sets multiple key val pairs. It is possible to define a ttl (seconds).
Returns true on success.
const obj = { my: "Special", variable: 42 };
const obj2 = { my: "other special", variable: 1337 };
const success = myCache.mset([
{key: "myKey", val: obj, ttl: 10000},
{key: "myKey2", val: obj2},
])myCache.get( key )
Gets a saved value from the cache.
Returns a undefined if not found or expired.
If the value was found it returns the value.
value = myCache.get( "myKey" );
if ( value == undefined ){
// handle miss!
}
// { my: "Special", variable: 42 }Since 2.0.0:
The return format changed to a simple value and a ENOTFOUND error if not found *( as result instance of Error )
Since 2.1.0:
The return format changed to a simple value, but a due to discussion in #11 a miss shouldn't return an error.
So after 2.1.0 a miss returns undefined.
myCache.take( key )
get the cached value and remove the key from the cache.
Equivalent to calling get(key) + del(key).
Useful for implementing single use mechanism such as OTP, where once a value is read it will become obsolete.
myCache.set( "myKey", "myValue" )
myCache.has( "myKey" ) // returns true because the key is cached right now
value = myCache.take( "myKey" ) // value === "myValue"; this also deletes the key
myCache.has( "myKey" ) // returns false because the key has been deletedmyCache.mget( [ key1, key2, ..., keyn ] )
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.
value = myCache.mget( [ "myKeyA", "myKeyB" ] );
/*
{
"myKeyA": { my: "Special", variable: 123 },
"myKeyB": { the: "Glory", answer: 42 }
}
*/Since 2.0.0:
The method for mget changed from .get( [ "a", "b" ] ) to .mget( [ "a", "b" ] )
myCache.del( key )
Delete a key. Returns the number of deleted entries. A delete will never fail.
value = myCache.del( "A" );
// 1myCache.del( [ key1, key2, ..., keyn ] )
Delete multiple keys. Returns the number of deleted entries. A delete will never fail.
value = myCache.del( "A" );
// 1
value = myCache.del( [ "B", "C" ] );
// 2
value = myCache.del( [ "A", "B", "C", "D" ] );
// 1 - because A, B and C not existsmyCache.ttl( key, ttl )
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.
The key will be deleted when passing in a ttl < 0.
myCache = new NodeCache( { stdTTL: 100 } )
changed = myCache.ttl( "existentKey", 100 )
// true
changed2 = myCache.ttl( "missingKey", 100 )
// false
changed3 = myCache.ttl( "existentKey" )
// truemyCache.getTtl( key )
Receive the ttl of a key. You will get:
undefinedif the key does not exist0if this key has no ttl- a timestamp in ms representing the time at which the key will expire
myCache = new NodeCache( { stdTTL: 100 } )
// Date.now() = 1456000500000
myCache.set( "ttlKey", "MyExpireData" )
myCache.set( "noTtlKey", "NonExpireData", 0 )
ts = myCache.getTtl( "ttlKey" )
// ts wil be approximately 1456000600000
ts = myCache.getTtl( "ttlKey" )
// ts wil be approximately 1456000600000
ts = myCache.getTtl( "noTtlKey" )
// ts = 0
ts = myCache.getTtl( "unknownKey" )
// ts = undefinedmyCache.keys()
Returns an array of all existing keys.
mykeys = myCache.keys();
console.log( mykeys );
// [ "all", "my", "keys", "foo", "bar" ]myCache.has( key )
Returns boolean indicating if the key is cached.
exists = myCache.has( 'myKey' );
console.log( exists );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 in approximately bytes
vsize: 0 // global value size count in approximately bytes
}
*/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 in approximately bytes
vsize: 0 // global value size count in approximately bytes
}
*/myCache.flushStats()
Flush the stats.
myCache.flushStats();
myCache.getStats();
/*
{
keys: 0, // global key count
hits: 0, // global hit count
misses: 0, // global miss count
ksize: 0, // global key size count in approximately bytes
vsize: 0 // global value size count in approximately bytes
}
*/myCache.close()
This will clear the interval timeout which is set on check period option.
myCache.close();Fired when a key has been added or changed.
You will get the key and the value as callback argument.
myCache.on( "set", function( key, value ){
// ... do something ...
});Fired when a key has been removed manually or due to expiry.
You will get the key and the deleted value as callback arguments.
myCache.on( "del", function( key, value ){
// ... do something ...
});Fired when a key expires.
You will get the key and value as callback argument.
myCache.on( "expired", function( key, value ){
// ... do something ...
});Fired when the cache has been flushed.
myCache.on( "flush", function(){
// ... do something ...
});Fired when the cache stats has been flushed.
myCache.on( "flush_stats", function(){
// ... do something ...
});This project is MIT licensed.
