js-ttl
v1.1.2
Published
A simple javascript in memory cache for node
Downloads
10
Readme
Javascript time-to-live
TTL
The time to-live-cache is a cache that evicts items that are older than a time-to-live threshold (in milliseconds). see (https://github.com/clojure/core.cache/wiki/TTL)
What is JS-TTL?
JS-TTL, a simple in-memory cache for Node.js.
What is it useful for?
- Cuts down database overhead.
API
Instantiation new JSTTL([{options}])
Instantiating a js-ttl cache
- Where options takes the following
- ttl - sets the ttl policy of the cache to the ttl provided. Not providing a ttl policy will default the ttl policy to 1000 milliseconds / 1 second.
var JSTTL = require('js-ttl');
var cache = new JSTTL();
var customCache = new JSTTL({ttl: 1000 * 10}) //10 seconds
Inserting objects in the cache
cache.put(key, value, [optionalTTL])
- Inserts the key/value pair in the cache. If an
optionalTTL
is provided, the ttl policy for the key/value are set to the optionalTTL.
Retrieving objects in the cache
cache.get(key)
- Fetches a the corresponding key/value pair in the cache. Returns
null
if there is no matching key, or the key has expired
Deleting objects in the cache
cache.delete(key, [optionalCallback])
- Removes the key/value pair from the cache, along the ttl policy
Clearing the cache
cache.clearAll()
- Flushes the cache and removes all ttl policies.
Events
miss - If you perform a cache seek, or cache.get
and the key/value is not found in the cache,
js-ttl will emit a cache miss with the following payload {key: String}
var jsTTL = require('js-ttl');
var cache = new jsTTL();
cache.put('michael', 'jordan');
cache.on('expiration', function(payload) {
//1 second later
console.log('key: %s', payload.key);
console.log('value: %s', payload.value);
console.log('ttl: %s', payload.ttl);
});
expiration - If the time to live policy for a key/value pair has been reached,
js-ttl will emit a expiration
event with the following payload {key, String, value: Object, ttl: Number}
var jsTTL = require('js-ttl');
var cache = new jsTTL();
cache.put('michael', 'jordan');
cache.on('miss', function(payload) {
console.log('key: %s', payload.key); //2 seconds later
});
Examples
var jsTTL = require('js-ttl');
var cache = new jsTTL();
cache.put('foo', 'bar');
cache.put('hello', 'world', 1000);
cache.put('indices', [0, 1, 2, 3, 4, 5], 2000);
cache.put('user', {_id: '0123-456-789', name: ''}, 1000 * 60 * 60 * 24);
cache.get('foo');
setTimeout(function(){
cache.get('foo'); //returns undefined.
}, 10001);