This is a simple library that emulates memcache
functions using HTML5 localStorage
, so that you can cache data on the client
and associate an expiration time with each piece of data. If the localStorage
limit (~5MB) is exceeded, it tries to create space by removing the items that are closest to expiring anyway. If localStorage
is not available at all in the browser, the library degrades by simply not caching and all cache requests return null.
The library exposes these methods: set()
, get()
, remove()
, flush()
, flushExpired()
, bucket()
, setExpiryMilliseconds()
.
Stores the value in localStorage. Expires after specified number of minutes. Will not expire if time is not set.
key
(string)value
(Object|string)time
(number: optional)
boolean : True if the value was stored successfully.
Retrieves specified value from localStorage, if not expired.
key
(string)
string | Object : The stored value. If no value is available, null is returned.
Removes a value from localStorage.
key
(string)
Removes all lscache items from localStorage without affecting other data.
Removes all expired lscache items from localStorage without affecting other data.
Use buckets to make lscache partition data in to different buckets. i.e. Flushing a bucket only removes items in that bucket.
bucketName
(string)
Bucket : A Bucket instance.
Sets the number of milliseconds each time unit represents in the set() function's "time" argument. Sample values:
- 1: each time unit = 1 millisecond
- 1000: each time unit = 1 second
- 60000: each time unit = 1 minute (Default value)
- 3600000: each time unit = 1 hour
milliseconds
(number)
The interface should be familiar to those of you who have used memcache
, and should be easy to understand for those of you who haven't.
For example, you can store a string for 2 minutes using lscache.set()
:
lscache.set('greeting', 'Hello World!', 2);
You can then retrieve that string with lscache.get()
:
alert(lscache.get('greeting'));
You can remove that string from the cache entirely with lscache.remove()
:
lscache.remove('greeting');
You can remove all items from the cache entirely with lscache.flush()
:
lscache.flush();
You can remove only expired items from the cache entirely with lscache.flushExpired()
:
lscache.flushExpired();
You can also check if local storage is supported in the current browser with lscache.supported()
:
if (!lscache.supported()) {
alert('Local storage is unsupported in this browser');
return;
}
You can enable console warning if set fails with lscache.enableWarnings()
:
// enable warnings
lscache.enableWarnings(true);
// disable warnings
lscache.enableWarnings(false);
The library also takes care of serializing objects, so you can store more complex data:
lscache.set('data', {'name': 'Pamela', 'age': 26}, 2);
And then when you retrieve it, you will get it back as an object:
alert(lscache.get('data').name);
If you want to namespace some storage, so that all items can be flushed at once. Or you have multiple instances of lscache on a page, use the bucket system. Buckets have the same API as the top level lscache
(lscache
is actually a global bucket).
lscache.set('response', '...', 2);
const bucket = lscache.bucket('mythings');
bucket.set('path', '...', 2);
bucket.flush(); // only removes 'path' which was set in the `mythings` bucket
Bucket returns it's own instance so you can chain one command.
lscache.bucket('mythings').set('path', '...', 2);
The default unit for the set()
function's "time" argument is in minutes. A shorter time may be desired, for example, in unit tests. You can use lscache.setExpriryMilliseconds()
to select a finer granularity of time unit. This affects all buckets.
asyncTest('Testing set() and get() with different units', function() {´
var expiryMilliseconds = 1000; //time units is seconds
lscache.setExpiryMilliseconds(expiryMilliseconds);
var key = 'thekey';
var numExpiryUnits = 2; // expire after two seconds
lscache.set(key, 'some value', numExpiryUnits);
setTimeout(function() {
equal(lscache.get(key), null, 'We expect value to be null');
start();
}, expiryMilliseconds * numExpiryUnits + 1);
});
For more live examples, play around with the demo here: http://pamelafox.github.com/lscache/demo.html
This library was originally developed with the use case of caching results of JSON API queries to speed up my webapps and give them better protection against flaky APIs. (More on that in this blog post)
For example, RageTube uses lscache
to fetch Youtube API results for 10 minutes:
var key = 'youtube:' + query;
var json = lscache.get(key);
if (json) {
processJSON(json);
} else {
fetchJSON(query);
}
function processJSON(json) {
// ..
}
function fetchJSON() {
var searchUrl = 'http://gdata.youtube.com/feeds/api/videos';
var params = {
'v': '2', 'alt': 'jsonc', 'q': encodeURIComponent(query)
}
JSONP.get(searchUrl, params, null, function(json) {
processJSON(json);
lscache.set(key, json, 10);
});
}
It does not have to be used for only expiration-based caching, however. It can also be used as just a wrapper for localStorage
, as it provides the benefit of handling JS object (de-)serialization.
For example, the QuizCards Chrome extensions use lscache
to store the user statistics for each user bucket, and those stats are an array
of objects.
function initBuckets() {
var bucket1 = [];
for (var i = 0; i < CARDS_DATA.length; i++) {
var datum = CARDS_DATA[i];
bucket1.push({'id': datum.id, 'lastAsked': 0});
}
lscache.set(LS_BUCKET + 1, bucket1);
lscache.set(LS_BUCKET + 2, []);
lscache.set(LS_BUCKET + 3, []);
lscache.set(LS_BUCKET + 4, []);
lscache.set(LS_BUCKET + 5, []);
lscache.set(LS_INIT, 'true')
}
The lscache
library should work in all browsers where localStorage
is supported.
A list of those is here:
http://www.quirksmode.org/dom/html5.html
- Run
npm install
to install all the dependencies. - Run
npm run build
to build the library using rollup. - Run
npm test
to run the tests.