Convert Figma logo to code with AI

pamelafox logolscache

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

1,463
160
1,463
15

Top Related Projects

14,015

Cross-browser storage for all use cases, used across the web.

💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

21,334

Simple and fast JSON database

A lightweight clientside JSON document store,

Quick Overview

The lscache library is a lightweight client-side cache that uses the browser's localStorage and sessionStorage APIs to store and retrieve data. It provides a simple and efficient way to cache data in the browser, reducing the need for repeated network requests and improving the overall performance of web applications.

Pros

  • Lightweight and Efficient: The library is small in size and has a minimal impact on the overall application's performance.
  • Easy to Use: The API is straightforward and intuitive, making it easy to integrate into existing projects.
  • Cross-Browser Compatibility: The library works across a wide range of modern browsers, ensuring consistent behavior.
  • Flexible Caching Strategies: Developers can choose between session-based or persistent caching, depending on their application's needs.

Cons

  • Limited to Browser Storage: The library is limited to the browser's storage capabilities, which may not be suitable for large amounts of data or complex caching requirements.
  • No Automatic Expiration: The library does not provide automatic expiration of cached data, requiring developers to manually manage the cache's lifetime.
  • No Invalidation Mechanism: The library does not offer a built-in mechanism for invalidating cached data, which can be a concern in some use cases.
  • Potential Security Risks: Storing sensitive data in the browser's storage can pose security risks, and developers should exercise caution when using the library.

Code Examples

Here are a few examples of how to use the lscache library:

  1. Storing and Retrieving Data:
// Store data in the cache
lscache.set('myData', { name: 'John Doe', age: 30 }, 60); // Cache for 60 minutes

// Retrieve data from the cache
const data = lscache.get('myData');
console.log(data); // { name: 'John Doe', age: 30 }
  1. Removing Data from the Cache:
// Remove a specific item from the cache
lscache.remove('myData');

// Clear the entire cache
lscache.flush();
  1. Checking Cache Expiration:
// Check if a cached item has expired
if (lscache.isExpired('myData')) {
  console.log('Data has expired');
}
  1. Namespacing Cached Data:
// Store data with a namespace
lscache.set('myApp:userData', { name: 'Jane Doe', age: 25 }, 120); // Cache for 120 minutes

// Retrieve data with a namespace
const userData = lscache.get('myApp:userData');
console.log(userData); // { name: 'Jane Doe', age: 25 }

Getting Started

To use the lscache library in your project, follow these steps:

  1. Include the lscache.min.js file in your HTML:
<script src="https://cdn.jsdelivr.net/npm/lscache@1.3.0/lscache.min.js"></script>
  1. Start using the library in your JavaScript code:
// Store data in the cache
lscache.set('myData', { name: 'John Doe', age: 30 }, 60); // Cache for 60 minutes

// Retrieve data from the cache
const data = lscache.get('myData');
console.log(data); // { name: 'John Doe', age: 30 }

That's it! You can now use the lscache library to cache data in your web application.

Competitor Comparisons

14,015

Cross-browser storage for all use cases, used across the web.

Pros of store.js

  • Supports a wider range of storage types (localStorage, sessionStorage, memory)
  • Provides plugins for additional functionality (e.g., encryption, expiration)
  • Offers cross-browser compatibility, including older browsers

Cons of store.js

  • Larger file size and more complex codebase
  • Less focused on caching specifically
  • May have more overhead for simple use cases

Code Comparison

lscache:

lscache.set('key', 'value', 60); // Store for 60 minutes
var value = lscache.get('key');
lscache.remove('key');

store.js:

store.set('key', 'value')
store.get('key')
store.remove('key')
store.clearAll()
store.each(function(value, key) {
  console.log(key, '==', value)
})

Summary

lscache is a lightweight library focused specifically on caching with localStorage, offering built-in expiration functionality. It's simpler and more straightforward for basic caching needs.

store.js is a more comprehensive storage solution with broader browser support and additional features through plugins. It's more versatile but may be overkill for simple caching tasks.

Choose lscache for lightweight, expiration-focused localStorage caching, and store.js for more complex storage requirements across multiple storage types and browsers.

💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

Pros of localForage

  • Supports multiple storage backends (IndexedDB, WebSQL, localStorage)
  • Provides a simple, Promise-based API for easier asynchronous operations
  • Offers better performance for large datasets due to IndexedDB support

Cons of localForage

  • Larger file size and more complex implementation
  • May be overkill for simple caching needs
  • Requires additional setup and configuration

Code Comparison

localForage:

localforage.setItem('key', 'value').then(function() {
  return localforage.getItem('key');
}).then(function(value) {
  console.log(value);
}).catch(function(err) {
  console.log(err);
});

lscache:

lscache.set('key', 'value', 60); // Store for 60 minutes
var value = lscache.get('key');
console.log(value);

Key Differences

  • API Style: localForage uses Promises, while lscache uses synchronous calls
  • Storage Options: localForage supports multiple backends, lscache focuses on localStorage
  • Complexity: localForage offers more features but is more complex, lscache is simpler and lightweight
  • Use Cases: localForage is better for large datasets and complex storage needs, lscache is ideal for simple caching scenarios

Conclusion

Choose localForage for more robust storage capabilities and better performance with large datasets. Opt for lscache if you need a lightweight, simple caching solution primarily using localStorage.

21,334

Simple and fast JSON database

Pros of lowdb

  • Full-featured JSON database with query support
  • Supports multiple storage adapters (file, memory, localStorage)
  • More robust for complex data operations

Cons of lowdb

  • Larger file size and more dependencies
  • Potentially slower for simple key-value storage
  • More complex setup and usage for basic caching needs

Code Comparison

lowdb:

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const adapter = new FileSync('db.json')
const db = low(adapter)

db.set('user.name', 'typicode').write()

lscache:

lscache.set('user.name', 'typicode', 60);
const value = lscache.get('user.name');

Key Differences

  • lscache is focused on simple key-value caching with expiration, while lowdb provides a more comprehensive database-like functionality.
  • lowdb offers more flexibility in terms of storage options and complex querying, whereas lscache is designed specifically for localStorage with a simpler API.
  • lscache has a smaller footprint and is easier to integrate for basic caching needs, while lowdb is better suited for applications requiring more advanced data management features.

A lightweight clientside JSON document store,

Pros of Lawnchair

  • Flexibility: Lawnchair provides a flexible and extensible API, allowing developers to easily integrate it into their projects and customize its behavior.
  • Cross-browser Compatibility: Lawnchair is designed to work across a wide range of browsers, including legacy versions, ensuring a consistent experience for users.
  • Offline Support: Lawnchair can be used to store data locally, enabling offline functionality and improving the user experience.

Cons of Lawnchair

  • Complexity: Lawnchair's flexibility and extensibility can also make it more complex to set up and configure, especially for developers new to the library.
  • Maintenance: The Lawnchair project has not been actively maintained in recent years, which may raise concerns about its long-term viability and support.

Code Comparison

Here's a brief code comparison between Lawnchair and lscache:

Lawnchair:

var db = new Lawnchair({name:'mydb'}, function() {
  this.save({key:'foo', value:'bar'}, function() {
    this.get('foo', function(obj) {
      console.log(obj.value); // 'bar'
    });
  });
});

lscache:

lscache.set('foo', 'bar', 60); // Store 'bar' under the key 'foo' for 60 seconds
var value = lscache.get('foo'); // Retrieve the value stored under the key 'foo'
console.log(value); // 'bar'

As you can see, lscache provides a more straightforward and concise API for basic caching operations, while Lawnchair offers a more feature-rich and flexible approach, which may be more suitable for complex use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.

NPM DownloadsLast 30 Days