• Stars
    star
    1,453
  • Rank 32,372 (Top 0.7 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 14 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A localStorage-based memcache-inspired client-side caching library.

lscache

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.

Methods

The library exposes these methods: set(), get(), remove(), flush(), flushExpired(), setBucket(), resetBucket(), setExpiryMilliseconds().


lscache.set

Stores the value in localStorage. Expires after specified number of minutes.

Arguments

  1. key (string)
  2. value (Object|string)
  3. time (number: optional)

Returns

boolean : True if the value was stored successfully.


lscache.get

Retrieves specified value from localStorage, if not expired.

Arguments

  1. key (string)

Returns

string | Object : The stored value. If no value is available, null is returned.


lscache.remove

Removes a value from localStorage.

Arguments

  1. key (string)

lscache.flush

Removes all lscache items from localStorage without affecting other data.


lscache.flushExpired

Removes all expired lscache items from localStorage without affecting other data.


lscache.setBucket

Appends CACHE_PREFIX so lscache will partition data in to different buckets.

Arguments

  1. bucket (string)

lscache.resetBucket

Removes prefix from keys so that lscache no longer stores in a particular bucket.


lscache.setExpiryMilliseconds

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

Arguments

  1. milliseconds (number)

Usage

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 have multiple instances of lscache running on the same domain, you can partition data in a certain bucket via:

lscache.set('response', '...', 2);
lscache.setBucket('lib');
lscache.set('path', '...', 2);
lscache.flush(); //only removes 'path' which was set in the lib bucket

The default unit for the set() function's "time" argument is 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:

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

Real-World Usage

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')
}

Browser Support

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

Building

For contributors:

  • Run npm install to install all the dependencies.
  • Run grunt. The default task will check the files with jshint, minify them, and use browserify to generate a bundle for testing.
  • Run grunt test to run the tests.

For repo owners, after a code change:

  • Run grunt bump to tag the new release.
  • Run npm login, npm publish to release on npm.

More Repositories

1

font-previewer-extension

Google Font Previewer Chrome Extension
JavaScript
68
star
2

python-project-template

A Github template repository for a Python project with support for Codespaces, devcontainer, and Github Actions.
Dockerfile
41
star
3

bootstrap-transloadit-plugin

A Bootstrap plugin for Transloadit uploads.
JavaScript
32
star
4

rag-on-postgres

This repo has moved! See new URL in README or below
Bicep
31
star
5

recursive-visualizations

An online tool to visualize recursive JS functions step-by-step as a tree.
HTML
29
star
6

dis-this

An online tool to disassemble Python code
JavaScript
26
star
7

mp3-text-sync

JavaScript for manually syncing an MP3 and text together, using a google spreadsheet as a backend.
HTML
24
star
8

python-web-apps

Teaching materials about Python Web Apps - slides and links to samples.
HTML
23
star
9

5lide

HTML5-based slides make for App Engine
JavaScript
22
star
10

meetupgator

An aggregator for upcoming events from Meetup groups. See them all in one place.
JavaScript
20
star
11

improvlists

A site for cataloging improv games and making set lists of them
19
star
12

ragetube

A way to watch Rage playlists online using Youtube videos.
Python
19
star
13

fastapi-azure-function-apim

A FastAPI app that is designed for deployment to Azure Functions with an API Management Policy.
Bicep
17
star
14

pamelafox-site

My personal homepage.
HTML
16
star
15

translation-telephone

A fun online version of the classic "Telephone" game - pass a message through a sequence of random languages and see what comes out!
Bicep
16
star
16

developer-support-handbook

See at http://pamelafox.github.io/developer-support-handbook/
HTML
14
star
17

youtube-feed-hider

A Chrome extension for hiding the feed on Youtube.com
CSS
14
star
18

baby-type-n-play

Baby Type'N'Play: let your baby smash your keyboard and only cause minimal chaos!
JavaScript
13
star
19

opml-generator

An App Engine app that generates OPMLs from spreadsheets.
Python
12
star
20

chrome-cards

Flash cards chrome extensions
JavaScript
11
star
21

fathomjs-codemirror-example

An example of using FathomJS and CodeMirror together for interactive HTML5 slides with code snippets.
CSS
9
star
22

django-quiz-app

A sample Django app for quizzes. Designed for deployment with the Azure Developer CLI.
Bicep
9
star
23

brackets-MDNLookup-extension

Brackets extension to lookup on MDN.
JavaScript
8
star
24

regression-model-azure-demo

A demonstration of running a regression model on Azure functions.
HTML
8
star
25

similarityweb

A way to visualize similar books.
CSS
8
star
26

staticmaps-function

A FastAPI that can generate maps using the py-staticmaps package. Designed for deployment to Azure Functions + Azure CDN, using the Azure Developer CLI and Bicep files.
Bicep
8
star
27

resolutionizer

Simple page for testing a webpage at different screen resolutions
8
star
28

multirecorder

A library for recording multiple sounds from your mic, deleting them, and combining them together.
7
star
29

parallel-demo

An example of parallel programming in the browser for AP CSP.
JavaScript
6
star
30

python-crash-course

Public materials for Python Crash Course
HTML
5
star
31

smileyslider

A slider with a smiley exterior.
JavaScript
5
star
32

python-3.11-playground

Open this repo in Codespaces for a Python 3.11 environment.
Dockerfile
5
star
33

simple-fastapi-container

A simple FastAPI app that is containerized and designed for development on Azure Container Apps.
Python
5
star
34

flask-surveys-container-app

An example Flask app for public surveys (no user auth) designed to be run inside Docker and deployed to Azure Container Apps with the Azure Developer CLI.
Bicep
5
star
35

pytest-axe-playwright-snapshot

A pytest plugin that runs Axe-core on Playwright pages and takes snapshots of the results.
Python
4
star
36

eatdifferent

A site encouraging people to eat different.
JavaScript
4
star
37

learningblog

A blog of technical learnings, built using Hyde, deployed on App Engine.
4
star
38

primalpaleorecipes

A portal that aggregates recipe resources.
JavaScript
4
star
39

my-py-talks

My Python talks
HTML
3
star
40

simple-flask-server-example

A very simple Python Flask server (classroom example)
Bicep
3
star
41

twitter-unhooked

A Chrome extension for hiding unneeded/addictive parts of Twitter.com
CSS
3
star
42

recoverymission

Powerhouse Recovery Mission
JavaScript
3
star
43

embedded-chat

A simple embeddable chat room for Coursera classes, distributed via Chrome extension.
JavaScript
3
star
44

projecticebreak

A website with tips for event attendees and organizers to make networking easier.
HTML
3
star
45

nsw-suburbs

A hack made at Apps4NSW that matches NSW suburb names to UK towns.
Python
3
star
46

ollama-python-playground

A dev container with ollama and ollama examples with the Python OpenAI SDK
Jupyter Notebook
3
star
47

hw-rspec-rails-intro

Ruby
2
star
48

pamelafox

Repository for my Github profile
2
star
49

hunters-haven

An LED backlit sign with animations controlled by the Amazon Alexa Skills API and a Particle Photon
JavaScript
2
star
50

mashups-mixmash

Mashups talk for NZ mix and mash.
2
star
51

python-sdk

Facebook Platform Python SDK
Python
2
star
52

medium-feed-hider

A Chrome extension for hiding the feed on Medium.com
JavaScript
2
star
53

html-slides-for-programming

A talk about using HTML slides for programming classes, with examples and resources.
HTML
2
star
54

recipe-search-extension

A simple Chrome extension that does a Google custom search.
2
star
55

simple-fastapi-azure-function

Simple HTTP API using FastAPI framework, deployed to Azure Functions using Azure Developer CLI.
Bicep
2
star
56

babybuddy-azure

Bicep
2
star
57

berkeleyside-unhooked

A Chrome extension for removing comments, color, and social media from Berkeleyside
CSS
2
star
58

simple-flask-api-container

A simple Flask API app that is containerized and designed for development on Azure Container Apps.
Python
2
star
59

simple-flask-api-azure-function

Simple HTTP API using Flask framework, deployed to Azure Functions using Azure Developer CLI.
Bicep
2
star
60

htmlescaper

Chrome extension for escaping HTML in textareas with right-click menu.
JavaScript
1
star
61

python-3.10-playground

Open this repo in Codespaces for a Python 3.10 environment.
Dockerfile
1
star
62

python-project-aug16

Example project for workflow lecture
Python
1
star
63

msdocs-django-postgresql-sample-infra

Just the infrastructure files for a Django PostgreSQL app on App Service
Bicep
1
star
64

chatapp-evaltools-cli

A CLI for evaluation tools for chat apps
Python
1
star
65

pystar-tutorial

Tutorial for Pystar
Python
1
star
66

hw-bdd-cucumber

Ruby
1
star
67

gdisf-jquery-intro

jQuery Intro Exercises
JavaScript
1
star
68

software-eng-lectures

Some lecture slides for software eng class
HTML
1
star
69

feature-detection-io

Feature detection slides
JavaScript
1
star
70

translation-telephone-extension

Chrome Extension for Translation Telephone.
1
star
71

python-project-mar29th

wharevew
Python
1
star
72

python-azd-template

Best practices for Python azd templates
1
star
73

hangout-scheduler

An App Engine app for scheduling Google+ Hangouts.
Python
1
star
74

ka-slideshow-example

Example slideshow JS library for Khan Academy tutorial on libraries.
JavaScript
1
star
75

learnlive-rag-starter

Starter code for RAG app for learn live session
Python
1
star
76

flask-charts-api-container-app

An example Flask app for a chart generator API designed to be run inside Docker and deployed to Azure Container Apps with the Azure Developer CLI.
Bicep
1
star
77

python-3.13-playground

A simple Python 3.13 dev container
Dockerfile
1
star
78

python-openai-demos

A series of short examples using the OpenAI SDK
Python
1
star