Receptacle
In memory cache for node and the browser that supports lru
and ttl
algorithms.
Items in the cache will move to the back queue when accessed and any key can optionally have an expiry time.
Installation
Npm
npm install receptacle
<script type="text/javascript" src="receptacle.js"></script>
<script>
define(['receptacle'], function (receptacle) {...})
window.receptacle
</script>
Example
var Receptacle = require('receptacle');
var cache = new Receptacle({ max: 100 });
cache.set("item", 1, { ttl: 100 });
cache.get("item");
cache.has("item");
cache.expire("item", 50);
cache.delete("item");
cache.clear();
cache.set("item", 1, { ttl: 100, refresh: true });
cache.get("item");
cache.set("item", 1, { meta: { custom: 1 } });
cache.meta("item");
Serialization
You can easily serialize and rehydrate your cache as JSON.
var Receptacle = require('receptacle');
var cache = new Receptacle({ max: 5 });
cache.set("a", 1, { ttl: 1000 });
var serialized = JSON.stringify(cache);
var newCacheFromJSON = new Receptacle(JSON.parse(serialized));
API
###Receptacle({ max=Infinity, items=[], id=# })
Create a new cache.
####id
Each cache is assigned a unique id for organizing, you can optionally provide an id during instanciation.
####max
Get the maximum size of the cache (default of Infinity).
####size
Get the current number of items in the cache.
####has(key)
Check if a key is in the cache, even if it's undefined.
####get(key)
Retreive a key from the cache.
####meta(key)
If a meta option was used with setting an item in the cache it will be returned.
####set(key, value, options)
Set a key in the cache, optionally setting a ttl
option that will cause the value to expire.
If a refresh
option is true
the ttl will automatically reset when the key
is accessed.
####delete(key)
Immediately remove a key from the cache.
####expire(key, [ms=0])
Update the expire time for a key. You can also use any valid ms string for a timeout.
####clear()
Remove all keys from the cache.
Contributions
- Use
npm test
to run tests.
Please feel free to create a PR!