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.
HTML5本地存储API(Web存储的一部分)具有出色的浏览器支持 ,并且正在越来越多的应用程序中使用。 它具有简单的API,当然也有其缺点,类似于cookie。
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.
在过去的一年左右的时间里,我遇到了许多使用localStorage API的工具和库,因此我将其中许多工具和库一起编译,并提供了一些代码示例和功能讨论。
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是localStorage API的包装,可让您使用许多有用的方法和功能。 例如,虽然localStorage仅限于存储字符串,但Lockr允许您存储不同的数据类型,而无需自己进行转换:
Lockr.set('website', 'SitePoint'); // string Lockr.set('categories', 8); // number Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]); // objectOther features include:
其他功能包括:
Retrieve all key/value pairs with the Lockr.get() method
使用Lockr.get()方法检索所有键/值对
Compile all key/value pairs into an array with Lockr.getAll()
使用Lockr.getAll()所有键/值对编译为数组
Delete all stored key/value pairs with Lockr.flush()
使用Lockr.flush()删除所有存储的键/值对
Add/remove values under a hash key using Lockr.sadd and Lockr.srem
使用Lockr.sadd和Lockr.srem在哈希键下添加/删除值
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:
一个1KB的库,使用localStorage作为通信通道,可以方便地在同一浏览器中的选项卡之间交换消息。 包含库之后,可以使用以下示例代码:
// 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.
如图所示, send()方法创建并发送消息, subscribe()方法使您可以侦听指定的消息。 您可以在此博客文章中阅读有关库的更多信息 。
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.
该库提供了类似Redis的API,在localStorage之上具有“快速的原子持久存储层”。 下面是从仓库的自述文件中摘录的示例代码片段。 它演示了许多可用的方法。
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.
该API的其他功能包括能够获取带有起始/结束值的范围,获取项数组以及压缩整个数据存储以节省空间的功能。 回购对所有方法及其作用都有完整的参考 。
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.”
这是另一个包装器,类似于Lockr,但是这次通过后备提供了更深的浏览器支持。 自述文件解释说:“ store.js在可用时使用localStorage,并依赖于IE6和IE7中的userData行为。 无闪存可减慢页面加载速度。 没有cookie可以增加您的网络请求。”
The basic API is explained in comments in the following code:
以下代码的注释中说明了基本API:
// 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).
GitHub存储库上的自述文件详细介绍了浏览器支持的深度以及潜在的错误和陷阱(例如,某些浏览器不允许以私有模式进行本地存储的事实)。
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是另一个localStorage包装器,但具有一些额外的功能。 您可以将其用作简单的localStorage API,也可以使用模仿内存对象缓存系统Memcached的功能。
lscache exposes the following methods, described in the comments in the code:
lscache公开了以下方法,如代码注释中所述:
// 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使您可以将数据划分为“存储桶”。 看一下这段代码:
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.
请注意,在第二个日志中,结果如何为null 。 这是因为我在记录结果之前已经设置了自定义存储桶。 设置存储桶后,即使我尝试刷新它,也无法访问在此之前添加到lscache的任何内容。 仅“其他”存储桶中的项目可访问或可刷新。 然后,当我重置存储桶时,我可以再次访问我的原始数据。
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.
secStore.js是一种数据存储API,它通过Stanford Javascript加密库添加了可选的安全层。 secStore.js允许您选择存储方法:localStorage,sessionStorage或cookie。 要使用secStore.js,您还必须包含上述sjcl.js库。
Here is an example demonstrating how to save some data with the encrypt option set to ‘true’:
这是一个示例,演示如何在encrypt选项设置为'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:
请注意,正在使用set()方法,该方法传递您指定的选项(包括自定义数据)以及允许您测试结果的回调函数。 然后,我们可以使用get()方法检索该数据:
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:
如果要使用会话存储或cookie而不是通过secStore.js使用本地存储,则可以在以下选项中进行定义:
var options = { encrypt: true, storage: 'session', // or 'cookies' data: { key: 'data here' } };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.
该库由Mozilla构建,为您提供了一个类似于localStorage的简单API,但是通过IndexedDB或WebSQL使用异步存储。 该API与localStorage( getItem() , setItem()等)完全相同,不同之setItem()于其API是异步的,并且语法要求使用回调。
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:
关于localForage的其他几点:
Supports use of JavaScript promises 支持使用JavaScript Promise 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
使您可以使用config()方法设置数据库信息
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.js被描述为统一的localStorage,sessionStorage和cookie API,它包含一些独特且非常易于使用的功能。 可以使用如下所示的基本方法:
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.js来测试localStorage是否可用:
basil.check('local'); // returns Boolean valueBasil.js also lets you use cookies or sessionStorage:
Basil.js还允许您使用cookie或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:
最后,在options对象时,可以定义以下与options对象:
Namespaces for different parts of your data 数据不同部分的命名空间 Priority order for which storage method to use 使用哪种存储方式的优先顺序 The default storage method 默认存储方式 An expire date for cookies. Cookie的过期日期。 options = { namespace: 'foo', storages: ['cookie', 'local'], storage: 'cookie', expireDays: 31 };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:
lz-string实用程序使您可以通过使用压缩将大量数据存储在localStorage中,并且使用起来非常简单。 在页面上包含库之后,您可以执行以下操作:
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.
注意使用compress()和decompress()方法。 上面代码中的注释显示了压缩前后的长度值。 您可以看到客户端存储空间总是有限,这将带来多大的好处。
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.
如该库的文档中所述 ,有一些选项可以将数据压缩到Uint8Array(JavaScript中的一种新数据类型),甚至可以压缩数据以存储在客户端之外。
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.
上面的工具可能会帮助您在localStorage中完成几乎所有您想做的事情,但是如果您需要更多功能,这里有一些其他相关工具和库可能需要您检出。
LokiJS – A fast, in-memory document-oriented datastore for node.js, browser, and Cordova.
LokiJS –一种快速的内存中面向文档的数据存储,用于node.js,浏览器和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.
AngularJS的客户端存储–命名空间的Angular JS客户端存储。 写入localStorage,且cookie处于备用状态。 除Angular核心外,没有外部依赖项; 不依赖于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.
AlaSQL.js –用于浏览器和Node.jsJavaScript SQL数据库。 处理传统的关系表和嵌套的JSON数据(NoSQL)。 从localStorage,IndexedDB或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.
angular-locker –一个简单且可配置的抽象,用于角度项目中的本地/会话存储,提供功能强大且易于使用的流畅api。
jsCache – Enables caching of JavaScript files, CSS stylesheets, and images using localStorage.
jsCache –使用localStorage启用对JavaScript文件,CSS样式表和图像的缓存。
LargeLocalStorage – Overcomes various browser deficiencies to offer a large key-value store on the client.
LargeLocalStorage –克服各种浏览器缺陷,以在客户端上提供大型键值存储。
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.
如果您是在localStorage API或增强客户端存储的相关工具之上构建的,请随时在评论中让我们知道。
翻译自: https://www.sitepoint.com/9-javascript-libraries-working-with-local-storage/
相关资源:remoteStoragejs是一个JavaScript库用于在浏览器中本地存储用户数据