0.0.5 • Published 8 years ago

offline-storage v0.0.5

Weekly downloads
5
License
MIT
Repository
github
Last release
8 years ago

特性

  • 支持Promise风格异步链式调用
  • 对外暴露一致、简洁的localStorage-like接口api
  • 自动适配当前浏览器下最优的存储驱动
  • 统一key/value键值对式对象存取

支持的驱动

  • indexedDB(优先支持)
  • localStorage(后备支持)

接口暴露

  • set(key,value)
  • get(key)
  • has(key)
  • remove(key)
  • clear()
  • count()
  • forEach(callback)
  • all(...callback)

安装

npm install offline-storage --save

使用

import Storage from 'offline-storage'

参数配置

// 默认配置
const defaultConfig = {
  driver: 'indexedDB',

  // 强制使用某种驱动, 默认false.自适配, true时则不会适配.
  forcibly: false,
  dbName: '',
  storeName: '',
};

如果forcibly使用默认值false,storage将根据浏览器自动适配最佳的驱动,并优先使用indexedDB. 如果想强制指定某一种驱动,只需要将forcibly值设为true. 另外两个参数dbName,storeName分别为indexedDB 的库名与表名。

示例

    let storage = new Storage({
      driver: 'localStorage',
      forcibly: true
    });
    
    storage.get('key')
       .then(function(value) {})
       .catch(function(e){});

    storage.set('key', { something: true })
       .then(function() {})
       .catch(function(e){});

    storage.has('key')
       .then(function(bool) {})
       .catch(function(e){});

    storage.remove('key')
       .then(function() {})
       .catch(function(e){});

    storage.clear()
       .then(function() {})
       .catch(function(e){});

    storage.count()
       .then(function(integer) {})
       .catch(function(e){});

    let func = ()=>{ console.log('and') };
    storage.forEach(func)
       .then(function() {})
       .catch(function(e){});

    let funcs = [func1,func2,func3];
    storage.all(funcs)
       .then(function() {})
       .catch(function(e){});

浏览器兼容性

  • 小容量需求(2~10M),若使用localStorage驱动,兼容到所有现代浏览器和IE8.
  • 大容量需求,使用indexedDB,只兼容最新的现代浏览器.
驱动ChormeFirefox(Gecko)Internet ExploreOperaSafari(Webkit)
localStorage43.5810.54
indexedDB23、24(webkit)10、16(moz)10157.1

存储空间限制

  • localStorage在不同浏览器的不同版本下有不同的容量限制,范围为2~10M。
  • indexedDB驱动总容量没有限制。单个indexedDB在不同浏览器下会有不同的限制。比如firefox对超过50M的Blob会请求权限。

文档参考

http://www.html5rocks.com/en/tutorials/offline/storage/

https://html.spec.whatwg.org/multipage/webstorage.html

https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API/Using_IndexedDB