9个用于处理Local Storage的JavaScript库

jopen 9年前

The HTML5 Local Storage API (part of Web Storage) has excellent browser support and is being used in more and more applications. It has a simple API and certainly has its drawbacks, similar to cookies.

Over the past year or so I’ve come across quite a few tools and libraries that use the localStorage API so I’ve compiled many of them together into this post with some code examples and discussion of the features.

Lockr

Lockr is a wrapper for the localStorage API and lets you use a number of useful methods and features. For example, while localStorage is limited to storing only strings, Lockr lets you store different data types without the need to do the conversion yourself:

Lockr.set('website', 'SitePoint'); // string  Lockr.set('categories', 8); // number  Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]);  // object

Other features include:

  • Retrieve all key/value pairs with the Lockr.get() method
  • Compile all key/value pairs into an array with Lockr.getAll()
  • Delete all stored key/value pairs with Lockr.flush()
  • Add/remove values under a hash key using Lockr.sadd and Lockr.srem

The Local Storage Bridge

A 1KB library to facilitate exchanging messages between tabs in the same browser, using localStorage as the communication channel. After including the library, here’s some sample code you might use:

// send a message  lsbridge.send('my-namespace', {     message: 'Hello world!'   });    // listen for messages  lsbridge.subscribe('my-namespace', function(data) {    console.log(data); // prints: 'Hello world!'  });

As shown, the send() method creates and sends the message and the subscribe() method lets you listen for the specified message. You can read more about the library in this blog post.

Barn

This library provides a Redis-like API with a “fast, atomic persistent storage layer” on top of localStorage. Below is an example code snippet taken from the repo’s README. It demonstrates many of the methods available.

var barn = new Barn(localStorage);    barn.set('key', 'val');  console.log(barn.get('key')); // val    barn.lpush('list', 'val1');  barn.lpush('list', 'val2');  console.log(barn.rpop('list')); // val1  console.log(barn.rpop('list')); // val2    barn.sadd('set', 'val1');  barn.sadd('set', 'val2');  barn.sadd('set', 'val3');  console.log(barn.smembers('set')); // ['val1', 'val2', 'val3']  barn.srem('set', 'val3');  console.log(barn.smembers('set')); // ['val1', 'val2']

Other features of the API include the ability to get ranges with start/end values, getting an array of items, and condensing the entire store of data to save space. The repo has a full reference of all the methods and what they do.

store.js

This is another wrapper, similar to Lockr, but this time provides deeper browser support via fallbacks. The README explains that “store.js uses localStorage when available, and falls back on the userData behavior in IE6 and IE7. No flash to slow down your page load. No cookies to fatten your network requests.”

The basic API is explained in comments in the following code:

// Store 'SitePoint' in 'website'  store.set('website', 'SitePoint');    // Get 'website'  store.get('website');    // Remove 'website'  store.remove('website');    // Clear all keys  store.clear();

In addition, there are some more advanced features:

// Store an object literal; uses JSON.stringify under the hood  store.set('website', {    name: 'SitePoint',    loves: 'CSS'  });    // Get the stored object; uses JSON.parse under the hood  var website = store.get('website');  console.log(website.name + ' loves ' + website.loves);    // Get all stored values  console.log(store.getAll());    // Loop over all stored values  store.forEach(function(key, val) {    console.log(key, val);  });

The README on the GitHub repo has lots of details on depth of browser support and potential bugs and pitfalls to consider (e.g. the fact that some browsers don’t allow local storage in private mode).

lscache

lscache is another localStorage wrapper but with a few extra features. You can use it as a simple localStorage API or you can use the features that emulate Memcached, a memory object caching system.

lscache exposes the following methods, described in the comments in the code:

// set a greeting with a 2 minute expiration  lscache.set('greeting', 'Hello World!', 2);    // get and display the greeting  console.log(lscache.get('greeting'));    // remove the greeting  lscache.remove('greeting');    // flush the entire cache of items  lscache.flush();    // flush only expired items  lscache.flushExpired();

Like the previous library, this one also takes care of serialization, so you can store and retrieve objects:

lscache.set('website', {    'name': 'SitePoint',    'category': 'CSS'  }, 4);    // retrieve data from the object  console.log(lscache.get('website').name);  console.log(lscache.get('website').category);

And finally, lscache lets you partition data into “buckets”. Take a look at this code:

lscache.set('website', 'SitePoint', 2);  console.log(lscache.get('website')); // 'SitePoint'    lscache.setBucket('other');  console.log(lscache.get('website')); // null    lscache.resetBucket();  console.log(lscache.get('website')); // 'SitePoint'

Notice how in the 2nd log, the result is null. This is because I’ve set a custom bucket before logging the result. Once I’ve set a bucket, anything added to lscache before that point will not be accessible, even if I try to flush it. Only the items in the ‘other’ bucket are accessible or flushable. Then when I reset the bucket, I’m able to access my original data again.

secStore.js

secStore.js is a data storage API that adds an optional layer of security by means of the Stanford Javascript Crypto Library. secStore.js lets you choose your storage method: localStorage, sessionStorage, or cookies. To use secStore.js, you have to also include the aforementioned sjcl.js library.

Here is an example demonstrating how to save some data with the encrypt option set to ‘true’:

var storage = new secStore;  var options = {      encrypt: true,        data: {          key: 'data goes here'        }      };    storage.set(options, function(err, results) {    if (err) throw err;    console.log(results);  });

Notice the set() method being used, which passes in the options you specify (including the custom data) along with a callback function that lets you test the results. We can then use the get() method to retrieve that data:

storage.get(options, function(err, results) {    if (err) throw err;    console.log(results.key); // Logs: "data goes here"  });

If you want to use session storage or cookies instead of local storage with secStore.js, you can define that in the options:

var options = {    encrypt: true,    storage: 'session', // or 'cookies'    data: {      key: 'data here'    }  };

localForage

This library, built by Mozilla, gives you a simple localStorage-like API, but uses asynchronous storage via IndexedDB or WebSQL. The API is exactly the same as localStorage (getItem(), setItem(), etc), except its API is asynchronous and the syntax requires callbacks to be used.

So for example, whether you set or get a value, you won’t get a return value but you can deal with the data that’s passed to the callback function, and (optionally) deal with errors:

localforage.setItem('key', 'value', function(err, value) {    console.log(value);  });    localforage.getItem('key', function(err, value) {    if (err) {      console.error('error message...');    } else {      console.log(value);    }  });

Some other points on localForage:

  • Supports use of JavaScript promises
  • Like other libraries, not limited just to storing strings but you can set and get objects
  • Lets you set database information using a config() method

Basil.js

Basil.js is described as a unified localStorage, sessionStorage, and cookie API and it includes some unique and very easy to use features. The basic methods can be used as shown here:

basil = new Basil(options);    basil.set('foo', 'bar');  basil.get('foo');  basil.remove('foo');  basil.reset();

You can also use Basil.js to test if localStorage if available:

basil.check('local'); // returns Boolean value

Basil.js also lets you use cookies or sessionStorage:

basil.cookie.set(key, value, {     'expireDays': days, 'domain': 'mydomain.com'  });  basil.cookie.get(key);    basil.sessionStorage.set(key, value);  basil.sessionStorage.get(key);

Finally, in an options object, you can define the following with an options object:

  • Namespaces for different parts of your data
  • Priority order for which storage method to use
  • The default storage method
  • An expire date for cookies.
options = {    namespace: 'foo',    storages: ['cookie', 'local'],    storage: 'cookie',    expireDays: 31  };

lz-string

The lz-string utility lets you store large amounts of data in localStorage by using compression and it’s pretty straightforward to use. After including the library on your page, you can do the following:

var string = 'A string to test our compression.';  console.log(string.length); // 33  var compressed = LZString.compress(string);  console.log(compressed.length); // 18  string = LZString.decompress(compressed);

Notice the use of the compress() and decompress() methods. The comments in the above code show the length values before and after compression. You can see how beneficial this would be seeing how client side storage always has limited space.

As explained in the library’s docs, there are options to compress data to Uint8Array (a new-ish data type in JavaScript) and even the ability to compress the data for storage outside of the client.

Honorable Mentions

The above tools will probably help you do just about anything you want in localStorage, but if you’re looking for more, here are a few more related tools and libraries you might want to check out.

  • LokiJS – A fast, in-memory document-oriented datastore for node.js, browser, and Cordova.
  • Client Storage for AngularJS – Namespaced client storage for Angular JS. Writes to localStorage, with cookie fallback. No external dependencies other than Angular core; does not depend on ngCookies.
  • AlaSQL.js – JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.
  • angular-locker – A simple and configurable abstraction for local/session storage in angular projects, providing a fluent api that is powerful and easy to use.
  • jsCache – Enables caching of JavaScript files, CSS stylesheets, and images using localStorage.
  • LargeLocalStorage – Overcomes various browser deficiencies to offer a large key-value store on the client.

Know any others?

If you’ve built something on top of the localStorage API or a related tool that enhances client-side storage, feel free to let us know about it in the comments.