Localforage profile

Project address github.com/localForage…

Chinese address localforage.docschina.org/ API

When it comes to localStorage, the first thing we think of is localStorage storage, there are many people who have used it, but localStorage has the following disadvantages:

  1. Storage capacity is limited, most browsers should be up to 5M.
  2. Only strings are supported; if you store objects, you need to convert them using json.stringify and json.parse
  3. The reads are synchronous, which works fine in most cases, but if you are storing large data, such as base64 columns that store a large image, the readability may be delayed

Loaclforage has been designed to circumvent the shortcomings of localStorage above, while preserving the benefits of localStorage.

The advantage of Localforage is that the API is very simple and easy to use, so you can use both pretty much the same

The logic for localforage is to use IndexDB to store data in preference, or localStorage if the browser does not support WebSQL or if it still does not

Localforage provides the forage API as well as support for the ES6 Promises API, which you can choose to implement.

The installation

You can use NPM install localforage or bower install localforage

getItem(key, successCallback)

Get the value for the key from the repository and feed the result to the callback function. If the key does not exist, getItem() returns null.

GetItem () also returns null when undefined is stored. Unable to store undefined due to localStorage limitations and for compatibility reasons.

localforage.getItem('somekey').then(function(value) {// When the value in the offline repository is loaded, the code here runs console.log(value); }).catch(function(err) {// When an error occurs, the code here runs console.log(err); }); // Callback version: localforage. GetItem ('somekey'.function(err, value) {// This code runs console.log(value) when the value in the offline repository is loaded; });Copy the code

setItem(key, value, successCallback)

Save the data to an offline repository. You can store JavaScript objects of the following types

  • Array
  • ArrayBuffer
  • Blob
  • Float32Array
  • Float64Array
  • Int8Array
  • Int16Array
  • Int32Array
  • Number
  • Object
  • Uint8Array
  • Uint8ClampedArray
  • Uint16Array
  • Uint32Array
  • String

When using localStorage and WebSQL as a back end, binary data is serialized before being saved (and retrieved). When storing binary data, serialization results in an increase in size.

localforage.setItem('somekey'.'some value').then(function(value) {// After the value is stored, other operations can be performed console.log(value); }).catch(function(err) {// When an error occurs, the code here runs console.log(err); }); / / different fromlocalStorage, you can store non-string types localforage. SetItem ('my array'And [1, 2,'three']).then(function(value) {// Output '1' console.log(value[0]); }).catch(function(err) {// When an error occurs, the code here runs console.log(err); }); // You can even store binary data returned by AJAX responses req = new XMLHttpRequest(); req.open('GET'.'/photo.jpg'.true);
req.responseType = 'arraybuffer';

req.addEventListener('readystatechange'.function() {
    if(req.readyState === 4) {// readyState complete localforage. SetItem ('photo', req.response).then(function(image) {var blob = new blob ([image]); var imageURI = window.URL.createObjectURL(blob); }).catch(function(err) {// When an error occurs, the code here runs console.log(err); }); }});Copy the code



removeItem(key, successCallback)

Delete the value corresponding to the key from the offline repository.

localforage.removeItem('somekey').then(function() {// When the value is removed, the code here runs console.log('Key is cleared! ');
}).catch(function(err) {// When an error occurs, the code here runs console.log(err); });Copy the code

clear(successCallback)

Reset the database by deleting all keys from the database.

Localforage. Clear () will delete all values in the offline repository. Use this method with caution.

localforage.clear().then(function() {// When the database is completely deleted, the code here runs console.log('Database is now empty.');
}).catch(function(err) {// When an error occurs, the code here runs console.log(err); });Copy the code

length(successCallback)

Gets the number of keys in the offline warehouse (that is, the “length” of the data warehouse).

localforage.length().then(function(numberOfKeys) {// Output the size of the database console.log(numberOfKeys); }).catch(function(err) {// When an error occurs, the code here runs console.log(err); });Copy the code

key(keyIndex, successCallback)

Gets the name of the key based on its index

localforage.key(2).then(function(keyName) {// The key name console.log(keyName); }).catch(function(err) {// When an error occurs, the code here runs console.log(err); });Copy the code

keys(successCallback)

Get all the keys in the data warehouse

localforage.keys().then(function(keys) {// Array console.log(keys) with all keys; }).catch(function(err) {// When an error occurs, the code here runs console.log(err); });Copy the code

setDriver(driverName)

setDriver([driverName, nextDriverName])

If available, force specific drivers to be set

By default, localForage selects back-end drivers for the data warehouse in the following order:

  1. IndexedDB
  2. WebSQL
  3. localStorage

If you want to force a specific driver, you can use setDriver() with one or more of the following arguments:

  • localforage.INDEXEDDB
  • localforage.WEBSQL
  • localforage.LOCALSTORAGE

If the backend driver you are trying to load is not available on your browser, localForage will use one of the backend drivers you used previously. This means that if you try to force the Gecko browser to use WebSQL, you will fail and continue to use IndexedDB.

// Force settinglocalStorage is the back-end driver localforage. SetDriver (localforage.LOCALSTORAGE); // List the optional drivers to prioritize localforage. SetDriver ([localforage.WEBSQL, localforage.INDEXEDDB]);Copy the code

config(options)

Set the localForage option. In the call localForage

before

config()
setDriver()

driver

Name of the database. May appear in a database prompt. Generally use the name of your application. In localStorage, it prefixes all keys stored in localStorage.

  

name

Name of the database. May appear in a database prompt. Generally use the name of your application. In localStorage, it prefixes all keys stored in localStorage.

Default: ‘localforage’

size

The size of the database, in bytes. It is now only used for WebSQL

Default value: 4980736

storeName

The name of the data warehouse. In IndexedDB, it is dataStore; in WebSQL, it is the name of the database key/ Value key table. Contains only letters, digits, and underscores. Any non-alphanumeric characters are converted to underscores.

Default: ‘keyValuepairs’

version

The database version. Can be used for future upgrades; Currently unused.

Default value: 1.0

description

The description of the database is generally provided to the developer.

Default value:”

// Rename the database from "localforage" to "Hipster PDA App" localforage.config({name:'Hipster PDA App'}); // Will be used forciblylocalStorage acts as a Storage driver, even if other drivers are available. // Can be configured instead of 'setThe Driver () `. localforage.config({ driver: localforage.LOCALSTORAGE, name:'I-heart-localStorage'}); // Configure different driver priorities localforline. config({driver: [localforline. WEBSQL, localforline. INDEXEDDB, localforline. LOCALSTORAGE], name:'WebSQL-Rox'
});Copy the code

Reference address www.zhangxinxu.com/wordpress/2…