FormidableLabs/nodecache

Name: nodecache

Owner: Formidable

Description: a node internal caching module

Forked from: mpneuried/nodecache

Created: 2017-04-25 20:50:00.0

Updated: 2017-09-25 01:25:52.0

Pushed: 2017-04-25 21:11:37.0

Homepage: http://mpneuried.github.io/nodecache/

Size: 789

Language: CoffeeScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

node-cache

Build Status Windows Tests Dependency Status NPM version Coveralls Coverage

Gitter

NPM

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 (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.

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 either throw an error or call the callback with an error.

Install

m install node-cache --save

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

Examples:

Initialize (INIT):
t NodeCache = require( "node-cache" );
t myCache = new NodeCache();
Options
t NodeCache = require( "node-cache" );
t myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );
Store a key (SET):

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

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

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


Note: If the key expires based on it's ttl it will be deleted entirely from the internal data object.

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

= { my: "Special", variable: 42 };
ess = myCache.set( "myKey", obj, 10000 );
rue
Retrieve a key (GET):

myCache.get( key, [callback] )

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

che.get( "myKey", function( err, value ){
( !err ){
if(value == undefined){
  // key not found
}else{
  console.log( value );
  //{ my: "Special", variable: 42 }
  // ... do something ...
}


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

e = myCache.get( "myKey" );
 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 callback( err ) or on sync call 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.

Since 3.1.0 errorOnMissing option added


value = myCache.get( "not-existing-key", true );
tch( err ){
// ENOTFOUND: Key `not-existing-key` not found

Get multiple keys (MGET):

myCache.mget( [ 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.

che.mget( [ "myKeyA", "myKeyB" ], function( err, value ){
( !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.

e = 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" ] )

Delete a key (DEL):

myCache.del( key, [callback] )

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

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


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

e = myCache.del( "A" );

Delete multiple keys (MDEL):

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

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

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


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

e = myCache.del( "A" );


e = myCache.del( [ "B", "C" ] );


e = myCache.del( [ "A", "B", "C", "D" ] );
 - because A, B and C not exists
Change TTL (TTL):

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.

The key will be deleted when passing in a ttl < 0.

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



che.ttl( "missingKey", 100, function( err, changed ){
( !err ){
console.log( changed ); // false
// ... do something ...



che.ttl( "existendKey", function( err, changed ){
( !err ){
console.log( changed ); // true
// ... do something ...


Get TTL (getTTL):

myCache.getTtl( key, [callback] )

Receive the ttl of a key. You will get:

che = new NodeCache( { stdTTL: 100 } )

ate.now() = 1456000500000
che.set( "ttlKey", "MyExpireData" )
che.set( "noTtlKey", 0, "NonExpireData" )

 myCache.getTtl( "ttlKey" )
s wil be approximately 1456000600000

che.getTtl( "ttlKey", function( err, ts ){
( !err ){
// ts wil be approximately 1456000600000


s wil be approximately 1456000600000

 myCache.getTtl( "noTtlKey" )
s = 0

 myCache.getTtl( "unknownKey" )
s = undefined
List keys (KEYS)

myCache.keys( [callback] )

Returns an array of all existing keys.

sync
che.keys( function( err, mykeys ){
( !err ){
console.log( mykeys );
/ [ "all", "my", "keys", "foo", "bar" ]



ync
ys = myCache.keys();

ole.log( mykeys );
 "all", "my", "keys", "foo", "bar" ]
Statistics (STATS):

myCache.getStats()

Returns the statistics.

che.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
}

Flush all data (FLUSH):

myCache.flushAll()

Flush all data.

che.flushAll();
che.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
}

Close the cache:

myCache.close()

This will clear the interval timeout which is set on check period option.

che.close();

Events

set

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

che.on( "set", function( key, value ){
 ... do something ...  

del

Fired when a key has been removed manually or due to expiry. You will get the key and the deleted value as callback arguments.

che.on( "del", function( key, value ){
 ... do something ...  

expired

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

che.on( "expired", function( key, value ){
 ... do something ...  

flush

Fired when the cache has been flushed.

che.on( "flush", function(){
 ... do something ...  

Breaking changes
version 2.x

Due to the Issue #11 the return format of the .get() method has been changed!

Instead of returning an object with the key { "myKey": "myValue" } it returns the value itself "myValue".

version 3.x

Due to the Issue #30 and Issue #27 variables will now be cloned.
This could break your code, because for some variable types ( e.g. Promise ) its not possible to clone them.
You can disable the cloning by setting the option useClones: false. In this case it's compatible with version 2.x.

Benchmarks
Version 1.1.x

After adding io.js to the travis test here are the benchmark results for set and get of 100000 elements. But 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.

node.js 0.10.36
SET: 324ms ( 3.24µs per item )
GET: 7956ms ( 79.56µs per item )

node.js 0.12.0
SET: 432ms ( 4.32µs per item )
GET: 42767ms ( 427.67µs per item )

io.js v1.1.0
SET: 510ms ( 5.1µs per item )
GET: 1535ms ( 15.35µs per item )

Version 2.0.x

Again the same benchmarks by travis with version 2.0

node.js 0.6.21
SET: 786ms ( 7.86µs per item )
GET: 56ms ( 0.56µs per item )

node.js 0.10.36
SET: 353ms ( 3.53µs per item ) GET: 41ms ( 0.41µs per item )

node.js 0.12.2
SET: 327ms ( 3.27µs per item )
GET: 32ms ( 0.32µs per item )

io.js v1.7.1
SET: 238ms ( 2.38µs per item )
GET: 34ms ( 0.34µs per item )

As you can see the version 2.x will increase the GET performance up to 200x in node 0.10.x. This is possible because the memory allocation for the object returned by 1.x is very expensive.

Version 3.0.x

see travis results

node.js 0.6.21
SET: 786ms ( 7.24µs per item )
GET: 56ms ( 1.14µs per item )

node.js 0.10.38
SET: 353ms ( 5.41µs per item ) GET: 41ms ( 1.23µs per item )

node.js 0.12.4
SET: 327ms ( 4.63µs per item )
GET: 32ms ( 0.60µs per item )

io.js v2.1.0
SET: 238ms ( 4.06µs per item )
GET: 34ms ( 0.67µs per item )

until the version 3.0.x the object cloning is included, so we lost a little bit of the performance

Version 3.1.x

node.js v0.10.41
SET: 305ms ( 3.05µs per item )
GET: 104ms ( 1.04µs per item )

node.js v0.12.9
SET: 337ms ( 3.37µs per item )
GET: 167ms ( 1.67µs per item )

node.js v4.2.6
SET: 356ms ( 3.56µs per item )
GET: 83ms ( 0.83µs per item )

Compatibility

This module should work well back until node 0.6.x. But it's only tested until version 0.10.x because the build dependencies are not installable ;-) .

Release History

|Version|Date|Description| |:–:|:–:|:–| |4.1.1|2016-12-21|fix internal check interval for node < 0.10.25, thats teh default node for ubuntu 14.04. Thanks to Jimmy Hwang for for the pull #78; added more docker tests| |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.| |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.| |3.2.1|2016-03-21|Updated lodash to 4.x.; optimized grunt | |3.2.0|2016-01-29|Added method getTtl to get the time when a key expires. See #49| |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 for the pull #45. Added docker files and a script to run test on different node versions locally| |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 for the pull #44.| |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 and for #30 to Matthieu Sieben)| |~~2.2.0~~|~~2015-05-27~~|REVOKED VERSION, because of conficts. See Issue #30. So 2.2.0 is now 3.0.0| |2.1.1|2015-04-17|Passed old value to the del event. Thanks to Qix for the pull.| |2.1.0|2015-04-17|Changed get miss to return undefined instead of an error. Thanks to all #11 contributors | |2.0.1|2015-04-17|Added close function (Thanks to ownagedj). Changed the development environment to use grunt.| |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!| |1.1.0|2015-01-05|added .keys() method to list all existing keys| |1.0.3|2014-11-07|fix for setting numeric values. Thanks to kaspars + optimized key ckeck.| |1.0.2|2014-09-17|Small change for better ttl handling| |1.0.1|2014-05-22|Readme typos. Thanks to mjschranz| |1.0.0|2014-04-09|Made 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| |0.4.1|2013-10-02|Added the value to expired event| |0.4.0|2013-10-02|Added nodecache events| |0.3.2|2012-05-31|Added Travis tests|

NPM

Other projects

|Name|Description| |:–|:–| |rsmq|A really simple message queue based on redis| |redis-heartbeat|Pulse a heartbeat to redis. This can be used to detach or attach servers to nginx or similar problems.| |systemhealth|Node 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.| |rsmq-cli|a terminal client for rsmq| |rest-rsmq|REST interface for.| |redis-sessions|An advanced session store for NodeJS and Redis| |connect-redis-sessions|A connect or express middleware to simply use the redis sessions. With redis sessions you can handle multiple sessions per user_id.| |redis-notifications|A redis based notification engine. It implements the rsmq-worker to safely create notifications and recurring reports.| |nsq-logger|Nsq service to read messages from all topics listed within a list of nsqlookupd services.| |nsq-topics|Nsq helper to poll a nsqlookupd service for all it's topics and mirror it locally.| |nsq-nodes|Nsq helper to poll a nsqlookupd service for all it's nodes and mirror it locally.| |nsq-watch|Watch one or many topics for unprocessed messages.| |hyperrequest|A wrapper around hyperquest to handle the results| |task-queue-worker|A powerful tool for background processing of tasks that are run by making standard http requests |soyer|Soyer is small lib for server side use of Google Closure Templates with node.js.| |grunt-soy-compile|Compile Goggle Closure Templates ( SOY ) templates including the handling of XLIFF language files.| |backlunr|A solution to bring Backbone Collections together with the browser fulltext search engine Lunr.js| |domel|A simple dom helper if you want to get rid of jQuery| |obj-schema|Simple module to validate an object by a predefined schema|

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.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.