Skip to content

优秀的浏览器 IndexedDB 库 - localforage

Published: at 10:32 AMSuggest Changes

调用本地存储的 API 是一个很痛苦的过程,因为每个浏览器都有自己的 API,而且每个浏览器的 API 都不一样。localforage 是一个优秀的浏览器本地存储库,它可以让我们在不同的浏览器中使用相同的 API。

文档

官网

安装

npm install localforage

调用

import localforage from 'localforage';

使用

localforage.setItem('key', 'value').then(function (value) {
  // Do other things once the value has been saved.
  console.log(value);
}).catch(function(err) {
  // This code runs if there were any errors
  console.log(err);
});

获取

localforage.getItem('key').then(function(value) {
  // This code runs once the value has been loaded
  // from the offline store.
  console.log(value);
}).catch(function(err) {
  // This code runs if there were any errors
  console.log(err);
});

删除

localforage.removeItem('key').then(function() {
  // Run this code once the key has been removed.
  console.log('Key is cleared!');
}).catch(function(err) {
  // This code runs if there were any errors
  console.log(err);
});

清空

localforage.clear().then(function() {
  // Run this code once the database has been entirely deleted.
  console.log('Database is now empty.');
}).catch(function(err) {
  // This code runs if there were any errors
  console.log(err);
});

配置

localforage.config({
  driver      : localforage.INDEXEDDB, // Force WebSQL; same as using setDriver()
  name        : 'myApp',
  version     : 1.0,
  size        : 4980736, // Size of database, in bytes. WebSQL-only for now.
  storeName   : 'keyvaluepairs', // Should be alphanumeric, with underscores.
  description : 'some description'
});

事件

localforage.ready().then(function() {
  // Ready to use!
  console.log('ready');
}).catch(function(err) {
  // This code runs if there were any errors
  console.log(err);
});

本地存储

localforage.setDriver([
  localforage.INDEXEDDB,
  localforage.WEBSQL,
  localforage.LOCALSTORAGE
]).then(function() {
  // we're using a preferred driver
}).catch(function(err) {
  // we had to fallback to another driver
});

本地存储

localforage.getDriver().then(function(driverName) {
  // driverName is `localforage.INDEXEDDB`
  // if no preference is set, `localforage.LOCALSTORAGE` will be the next driver to
  // be used
}).catch(function(err) {
  // This code runs if there were any errors
  console.log(err);
});

本地存储

localforage.getDriver(localforage.INDEXEDDB).then(function() {
  // we're using IndexedDB
}).catch(function(err) {
  // we're using a different driver
});

多实例

var store = localforage.createInstance({
  name: "nameHere"
});

var otherStore = localforage.createInstance({
  name: "otherName"
});

// Setting the key on one of these doesn't affect the other.
store.setItem("key", "value");
otherStore.setItem("key", "value2");

Previous Post
Rollup 打包工具笔记
Next Post
优秀的 JavaScript 前端录制回放库 - rrweb