dexie、idb-keyval、localforage はいずれもブラウザの IndexedDB をより使いやすくするための JavaScript ライブラリです。IndexedDB は強力なクライアントサイドデータベースですが、低レベルで冗長な API のため、これらのライブラリは開発者の生産性を高めることを目的としています。dexie はフル機能のクエリエンジンとトランザクション制御を備えた ORM に近い設計です。idb-keyval は単純な key-value ストアとして動作し、最小限の API で即座に利用できます。localforage は localStorage に似たインターフェースを提供しつつ、バックエンドに IndexedDB(または WebSQL / localStorage)を使用することで、非同期かつ大容量のストレージを実現します。
dexie、idb-keyval、localforage はすべて IndexedDB をラップして使いやすくするライブラリですが、設計思想と用途が大きく異なります。それぞれの特徴を、実際のコードを交えて詳しく見ていきましょう。
dexie は明示的なテーブル定義とスキーマを持つ、本格的なデータベースライクな設計です。
// dexie: テーブルとインデックスの定義
import Dexie from 'dexie';
const db = new Dexie('MyApp');
db.version(1).stores({
friends: '++id, name, age', // 自動インクリメントID、name と age にインデックス
notes: '++id, title, &body' // body にユニークインデックス
});
idb-keyval は完全な key-value ストアで、1 つのストア内に任意のキーと値を保存します。
// idb-keyval: スキーマ不要、即時使用
import { get, set } from 'idb-keyval';
await set('user', { name: 'Alice', age: 30 });
const user = await get('user');
localforage も key-value モデルですが、複数の「インスタンス」で名前空間を分離できます。
// localforage: 名前付きインスタンス
import localforage from 'localforage';
const userStore = localforage.createInstance({ name: 'users' });
await userStore.setItem('alice', { age: 30 });
const alice = await userStore.getItem('alice');
dexie は豊富なクエリメソッドを提供します。
between)、部分一致(startsWith)、複合条件(and/or)など// dexie: 複雑なクエリ
const adults = await db.friends
.where('age')
.above(18)
.toArray();
const names = await db.friends
.where('name')
.startsWith('A')
.keys();
idb-keyval はキーによる直接取得のみをサポートします。
values())やキー一覧(keys())は可能だが、フィルタリングは自前実装// idb-keyval: キー指定での取得のみ
import { get, keys } from 'idb-keyval';
const user = await get('user-123');
// 条件検索はできない
localforage も同様に、キーによる取得と全件取得のみ。
keys() で全キーを取得後、自前でフィルタリングする必要あり// localforage: キーによる取得
const user = await localforage.getItem('user-123');
// 複雑な検索は不可能
dexie は明示的なトランザクション制御をサポートします。
// dexie: トランザクション
await db.transaction('rw', db.friends, db.notes, async () => {
await db.friends.add({ name: 'Bob' });
await db.notes.add({ title: 'Note for Bob' });
});
idb-keyval と localforage はトランザクションを公開していません。
// idb-keyval / localforage: トランザクションなし
await set('a', 1);
await set('b', 2);
// この2操作はアトミックではない
dexie は Promise ベースで、チェーン可能なクエリビルダーを提供します。
// dexie: Promise チェーン
const result = await db.friends
.where('age')
.above(25)
.sortBy('name');
idb-keyval も Promise 専用で、極めてシンプルな関数群です。
// idb-keyval: 単純な Promise 関数
const value = await get('key');
localforage は Promise とコールバックの両方をサポートします。
// localforage: 両方のスタイル
// Promise
const value = await localforage.getItem('key');
// コールバック
localforage.getItem('key', (err, value) => {
if (!err) console.log(value);
});
dexie と idb-keyval は IndexedDB にのみ依存します。
localforage は複数のストレージバックエンドを自動で切り替えます。
// localforage: バックエンド自動選択
// 開発者は意識する必要なし
dexie// dexie での例
db.version(1).stores({
todos: '++id, listId, completed, priority',
lists: '++id, name'
});
// 高優先度の未完了タスクを取得
const highPriority = await db.todos
.where('priority')
.equals('high')
.and(todo => !todo.completed)
.toArray();
idb-keyval// idb-keyval での例
await set('authToken', 'abc123');
const token = await get('authToken');
localStorage.setItem で書かれたコードがあるlocalforage// localforage での置き換え
// localStorage.setItem('user', JSON.stringify(user));
await localforage.setItem('user', user); // シリアライズ不要
| 特徴 | dexie | idb-keyval | localforage |
|---|---|---|---|
| データモデル | テーブル+インデックス | 単一 key-value | key-value(名前空間可) |
| クエリ能力 | 高度(範囲、部分一致等) | キー取得のみ | キー取得のみ |
| トランザクション | 明示的サポート | なし | なし |
| API スタイル | Promise + チェーン | Promise 関数 | Promise + コールバック |
| バックエンド | IndexedDB のみ | IndexedDB のみ | IndexedDB/WebSQL/localStorage |
| bundle size | やや大きめ | 極小 | 中程度 |
dexieidb-keyvallocalforageこれら3つのライブラリは、それぞれ異なる「痛み」を解決するために作られています。自分のプロジェクトが抱える課題に最もフィットするものを選ぶことが、長期的なメンテナンス性と開発速度の鍵になります。
localforage は既存の localStorage コードを非同期かつ大容量対応に置き換えたい場合に最適です。コールバックと Promise の両方をサポートし、バックエンドを自動で切り替えるため、古いブラウザとの互換性も考慮できます。ただし、IndexedDB の高度な機能(カスタムインデックス、複雑なクエリ)は利用できません。
idb-keyval は「ただ値を保存して取り出したい」だけのケースに最適です。API が localStorage に似ており、わずか 4 つの関数(get、set、del、clear)しか持たないため、導入・理解が極めて容易です。複雑なクエリやスキーマ管理は不要で、軽量さとシンプルさを重視するプロジェクトに適しています。
dexie は複雑なクエリ(範囲検索、インデックス、複合キーなど)やトランザクション制御が必要なアプリケーションに最適です。オフラインファーストの PWA や大量の構造化データを扱う場合に強みを発揮します。ただし、学習コストがやや高く、シンプルな key-value 用途にはオーバーキルになる可能性があります。
localForage is a fast and simple storage library for JavaScript. localForage
improves the offline experience of your web app by using asynchronous storage
(IndexedDB or WebSQL) with a simple, localStorage-like API.
localForage uses localStorage in browsers with no IndexedDB or WebSQL support. See the wiki for detailed compatibility info.
To use localForage, just drop a single JavaScript file into your page:
<script src="localforage/dist/localforage.js"></script>
<script>localforage.getItem('something', myCallback);</script>
Try the live example.
Download the latest localForage from GitHub, or install with npm:
npm install localforage
Lost? Need help? Try the localForage API documentation. localForage API文档也有中文版。
If you're having trouble using the library, running the tests, or want to contribute to localForage, please look through the existing issues for your problem first before creating a new one. If you still need help, feel free to file an issue.
Because localForage uses async storage, it has an async API. It's otherwise exactly the same as the localStorage API.
localForage has a dual API that allows you to either use Node-style callbacks or Promises. If you are unsure which one is right for you, it's recommended to use Promises.
Here's an example of the Node-style callback form:
localforage.setItem('key', 'value', function (err) {
// if err is non-null, we got an error
localforage.getItem('key', function (err, value) {
// if err is non-null, we got an error. otherwise, value is the value
});
});
And the Promise form:
localforage.setItem('key', 'value').then(function () {
return localforage.getItem('key');
}).then(function (value) {
// we got our value
}).catch(function (err) {
// we got an error
});
Or, use async/await:
try {
const value = await localforage.getItem('somekey');
// This code runs once the value has been loaded
// from the offline store.
console.log(value);
} catch (err) {
// This code runs if there were any errors.
console.log(err);
}
For more examples, please visit the API docs.
You can store any type in localForage; you aren't limited to strings like in
localStorage. Even if localStorage is your storage backend, localForage
automatically does JSON.parse() and JSON.stringify() when getting/setting
values.
localForage supports storing all native JS objects that can be serialized to JSON, as well as ArrayBuffers, Blobs, and TypedArrays. Check the API docs for a full list of types supported by localForage.
All types are supported in every storage backend, though storage limits in localStorage make storing many large Blobs impossible.
You can set database information with the config() method.
Available options are driver, name, storeName, version, size, and
description.
Example:
localforage.config({
driver : localforage.WEBSQL, // 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'
});
Note: you must call config() before you interact with your data. This
means calling config() before using getItem(), setItem(), removeItem(),
clear(), key(), keys() or length().
You can create multiple instances of localForage that point to different stores
using createInstance. All the configuration options used by
config are supported.
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");
You can use localForage with RequireJS:
define(['localforage'], function(localforage) {
// As a callback:
localforage.setItem('mykey', 'myvalue', console.log);
// With a Promise:
localforage.setItem('mykey', 'myvalue').then(console.log);
});
If you have the allowSyntheticDefaultImports compiler option set to true in your tsconfig.json (supported in TypeScript v1.8+), you should use:
import localForage from "localforage";
Otherwise you should use one of the following:
import * as localForage from "localforage";
// or, in case that the typescript version that you are using
// doesn't support ES6 style imports for UMD modules like localForage
import localForage = require("localforage");
If you use a framework listed, there's a localForage storage driver for the models in your framework so you can store data offline with localForage. We have drivers for the following frameworks:
If you have a driver you'd like listed, please open an issue to have it added to this list.
You can create your own driver if you want; see the
defineDriver API docs.
There is a list of custom drivers on the wiki.
You'll need node/npm and bower.
To work on localForage, you should start by
forking it and installing its
dependencies. Replace USERNAME with your GitHub username and run the
following:
# Install bower globally if you don't have it:
npm install -g bower
# Replace USERNAME with your GitHub username:
git clone git@github.com:USERNAME/localForage.git
cd localForage
npm install
bower install
Omitting the bower dependencies will cause the tests to fail!
You need PhantomJS installed to run local tests. Run npm test (or,
directly: grunt test). Your code must also pass the
linter.
localForage is designed to run in the browser, so the tests explicitly require a browser environment. Local tests are run on a headless WebKit (using PhantomJS).
When you submit a pull request, tests will be run against all browsers that localForage supports on Travis CI using Sauce Labs.
As of version 1.7.3 the payload added to your app is rather small. Served using gzip compression, localForage will add less than 10k to your total bundle size:
This program is free software; it is distributed under an Apache License.
Copyright (c) 2013-2016 Mozilla (Contributors).