9 JavaScript Libraries for Working with Local Storage
HTML5 local storage API (part of web storage) has excellent browser support and is being applied in more and more applications. It has a simple API, but it also has some disadvantages similar to cookies.
I have encountered quite a few tools and libraries using the localStorage API over the past year or so, so I have sorted them out into this post with some code examples and feature discussions.
Key points
- HTML5 local storage API is widely supported and is becoming more and more common in applications, but it also has some limitations similar to cookies. Various JavaScript libraries have been developed to improve and extend their capabilities.
- Lockr, store.js, and lscache provide wrappers for the localStorage API, providing additional usage methods and functions. These include storing different data types without manual conversion, deeper browser support, and simulation of Memcached memory object caching system.
- SecStore.js and localForage provide more professional features. secStore.js adds a layer of security through the Stanford Javascript Crypto Library, while localForage built by Mozilla provides an asynchronous storage API using IndexedDB or WebSQL.
- Other libraries such as Basil.js and lz-string provide unique features. Basil.js is a unified localStorage, sessionStorage, and cookie API that allows you to define namespaces, storage method priorities, and default storage. lz-string allows storage of large amounts of data in localStorage via compression.
Lockr
Lockr is a wrapper for the localStorage API that allows you to use many useful methods and features. For example, while localStorage is limited to storing strings, Lockr allows you to store different data types without having to convert them yourself:
1 2 3 4 |
|
Other functions include:
- Use the Lockr.get() method to retrieve all key-value pairs
- Compile all key-value pairs into an array using the Lockr.getAll() method
- Use the Lockr.flush() method to delete all stored key-value pairs
- Add/remove values under hash key using Lockr.sadd and Lockr.srem
The Local Storage Bridge
A 1KB library for using localStorage as a communication channel to facilitate message exchange between tabs in the same browser. Once the library is included, here is the sample code you can use:
1 2 3 4 5 6 7 8 9 |
|
As shown, the send() method creates and sends messages, and the subscribe() method allows you to listen for specified messages. You can read more about the library in this blog post.
Barn
This library provides a Redis-like API that provides a "fast, atomized persistent storage layer" on top of localStorage. Below is a sample code snippet taken from the README of the repo. It demonstrates many methods available.
1 2 3 4 |
|
API include the ability to use the start/end values to get ranges, get items arrays, and compress the entire data store to save space. This repo contains a complete reference to all methods and their functions.
store.js
This is another wrapper similar to Lockr, but this time it provides deeper browser support through fallback. README explains, "store.js uses localStorage when available and falls back to userData behavior in IE6 and IE7. There is no Flash to slow down page loading. There is no cookie to increase the burden on network requests."
The basic API is explained in the comments in the following code:
1 2 3 4 5 6 7 8 9 |
|
In addition, there are some more advanced features:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
README on GitHub repo details the depth of browser support and potential bugs and pitfalls to be considered (for example, some browsers do not allow local storage in privacy mode).
lscache
lscache is another localStorage wrapper, but with some extra features. You can use it as a simple localStorage API or use the functionality of emulating Memcached (memory object caching system).
lscache exposes the following method, which is described in the comments in the code:
1 2 3 4 5 6 7 8 9 10 11 |
|
Like the previous library, this library also handles serialization, so you can store and retrieve objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Finally, lscache allows you to divide data into "buckets". Check out this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Note that in the second log, the result is null. This is because I set up a custom bucket before logging the result. Once I set up a bucket, nothing added to lscache before this will be inaccessible, even if I try to refresh it. Only items in the "other" bucket are accessible or refreshable. Then when I reset the bucket I was able to access my original data again.
secStore.js
secStore.js is a data storage API that adds an optional security layer through the Stanford Javascript Crypto Library. secStore.js allows you to select storage methods: localStorage, sessionStorage, or cookie. To use secStore.js you must also include the sjcl.js library mentioned earlier.
The following is an example showing how to save some data with the encrypt option set to "true":
1 2 3 4 5 6 7 8 |
|
Note the set() method used, which passes in the options you specified (including custom data) and a callback function that allows you to test the results. Then, we can use the get() method to retrieve the data:
1 2 3 4 5 6 7 8 |
|
If you want to use sessionStorage or cookies instead of localStorage in secStore.js, you can define it in the options:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
localForage
This library built by Mozilla provides you with 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 that its API is asynchronous and the syntax requires the use of callbacks.
So for example, you won't get the return value regardless of whether you set or get the value, but you can handle the data passed to the callback function and (optional) handle the error:
1 2 3 4 |
|
Some other points about localForage:
- Support JavaScript Promise
- Like other libraries, it is not only limited to storing strings, but also setting and getting objects
- Allows you to set database information using the config() method
Basil.js
Basil.js is described as a unified localStorage, sessionStorage, and cookie API, which contains some unique and very easy to use features. The basic method can be used as follows:
1 2 3 4 5 6 7 8 9 |
|
You can also use Basil.js to test if localStorage is available:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Basil.js also allows you to use cookies or sessionStorage:
1 2 3 4 5 6 7 8 9 10 11 |
|
Finally, in the option object, you can use the option object to define the following:
- Namespaces for different parts of the data
- Preferential order of storage methods to be used
- Default storage method
- Expiration date of cookies
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
lz-string
lz-string utility allows you to store large amounts of data in localStorage by using compression, and it is very easy to use. After including the library on the page, you can do the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Please pay attention to the use of compress() and decompress() methods. The comments in the above code show the length values before and after compression. You can see how beneficial this will be, as client storage is always limited in space.
As explained in the library documentation, you can choose to compress the data into Uint8Array (a newer data type in JavaScript) and even compress the data to store externally on the client.
Honorable Mentions
The above tools may help you do almost everything you want to do in localStorage, but if you are looking for more, here are some more related tools and libraries you might want to check out.
- LokiJS – A fast, in-memory document-oriented data store for node.js, browsers, and Cordova.
- AngularJS client storage – Angular JS namespace client storage. Write to localStorage and fall back to cookie. There are no external dependencies except Angular core; ngCookies are not dependent.
- AlaSQL.js – JavaScript SQL database and Node.js for browsers. Handle traditional associated tables and nested JSON data (NoSQL). Export, store and import data from localStorage, IndexedDB, or Excel.
- angular-locker – Simple and configurable abstraction of local/session storage in Angular projects, providing a powerful and easy-to-use smooth API.
- jsCache – Enable cache of JavaScript files, CSS stylesheets, and images using localStorage.
- LargeLocalStorage – Overcome various browser flaws and provide large key-value storage on the client side.
Do you know other libraries?
If you have built some tools to enhance client storage on top of the localStorage API or related tools, feel free to let us know in the comments.
(The rest of the article is FAQ, which has been rewritten and streamlined according to the original text, and the original intention is maintained)
Frequently Asked Questions about JavaScript Local Repositories (FAQ)
Q: What are the benefits of using JavaScript local repositories?
A: JavaScript local repository provides many benefits. They provide a more efficient way to store data on the client side, which can significantly improve the performance of web applications. These libraries also provide a higher level of security than traditional data storage methods, as they allow data encryption. Additionally, they provide a more user-friendly interface for data management, making it easier for developers to use local storage.
Q: How does local storage work in JavaScript?
A: Local storage in JavaScript allows web applications to persist in storing data in a web browser. Unlike cookies, local storage does not expire and is not sent back to the server, making it a more efficient method of data storage. Data stored in local storage is saved across browser sessions, meaning it is still available even if the browser is closed and reopened.
Q: Can I use local storage for sensitive data?
A: While local storage provides a convenient way to store data on the client, it is not recommended to use it for storing sensitive data. This is because local storage is not designed as a secure storage mechanism. Data stored in local storage can be easily accessed and manipulated using simple JavaScript code. Therefore, sensitive data such as passwords, credit card numbers, or personal user information should not be stored in local storage.
Q: How to manage data in local storage?
A: Managing data in local storage involves three main actions: setting up items, getting items, and deleting items. To set the project, you can use the setItem() method, which accepts two parameters: key and value. To retrieve an item, you can use the getItem() method, which accepts the key as an argument and returns the corresponding value. To delete an item, you can use the removeItem() method, which accepts a key as an argument.
Q: What are some popular local JavaScript repositories?
A: There are several popular local repositories for JavaScript, including store.js, localForage, and js-cookie. Store.js provides a simple and consistent API for local storage and runs on all major browsers. LocalForage provides a powerful asynchronous storage API and supports IndexedDB, WebSQL and localStorage. Js-cookie is a lightweight library for handling cookies that can be used as a fallback when local storage is unavailable.
Q: How to check if local storage is available?
A: You can use the simple try/catch block in JavaScript to check if local storage is available. The window.localStorage property can be used to access local storage objects. Local storage is available if this property exists and can be used to set up and retrieve items.
Q: What is the storage limit for local storage?
A: The storage limits for local storage vary from browser to browser, but are usually around 5MB. This is much larger than the storage limit of cookies (only 4KB). However, it is better to be aware of the amount of data you store in your local storage, as too much data can slow down your web applications.
Q: Can local storage be shared between different browsers?
A: No, local storage cannot be shared between different browsers. Each web browser has its own independent local storage, so the data stored in one browser will not be available in another. This is important when designing web applications that rely on local storage.
Q: How to clear all data in local storage?
A: You can use the clear() method to clear all data in the local storage. This method does not accept any parameters and will delete all items from the local storage. Be careful when using this method, as it permanently deletes all data in the local storage.
Q: Can local storage be used on mobile devices?
A: Yes, local storage can be used on mobile devices. Most modern mobile web browsers support local storage, so you can use it on desktop and mobile devices to store data. However, storage limitations on mobile devices may be low, so it is important to consider this when designing web applications.
The above is the detailed content of 9 JavaScript Libraries for Working with Local Storage. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.
