資料儲存

Cordova 應用程式有多種儲存 API 可用。請參閱 html5rocks 儲存概觀教學,以獲得更完整的概述和範例。

每個 API 都有其優缺點,此處將總結說明。您應該選擇最適合您需求的 API。您也可以在同一個應用程式中針對不同目的使用多種不同的方法。

LocalStorage

Local storage 提供簡單、同步的鍵/值對儲存,並受所有 Cordova 平台上底層 WebView 實作的支援。

使用摘要

Local storage 可以透過 window.localStorage 存取。以下程式碼片段顯示返回的 Storage 物件所公開的最重要方法

var storage = window.localStorage;
var value = storage.getItem(key); // Pass a key name to get its value.
storage.setItem(key, value) // Pass a key name and its value to add or update that key.
storage.removeItem(key) // Pass a key name to remove that key from storage.

如需更多資訊,請參閱

優點

  • 所有 Cordova 平台皆支援。
  • 其簡單、同步的 API 表示它易於使用。

缺點

  • 僅儲存字串,因此複雜的資料結構必須序列化,且只能儲存可以序列化的資料。
  • 在處理大量資料時效能不佳。尤其
    • 由於缺少索引,表示搜尋需要手動迭代所有資料。
    • 由於需要序列化/反序列化,儲存大型或複雜的項目速度很慢。
    • 同步 API 表示呼叫會鎖定使用者介面。
  • 總儲存量有限(通常約為 5MB)。
  • iOS 會將 localStorage 資料儲存在作業系統在需要空間時可能會清除的位置。

IndexedDB

IndexedDB API 的目標是結合 LocalStorage 和 WebSQL API 的優點,同時避免它們的缺點。IndexedDB 可讓您儲存任意 JavaScript 物件(前提是它們受 結構化複製演算法 支援),並以金鑰建立索引。它提供一些 SQL 資料表的好處,而不會限制結構或需要在事前定義。

IndexedDB 提供一個簡單且易於理解的資料模型,與 LocalStorage 非常相似。但與 LocalStorage 不同的是,您可以建立多個資料庫,每個資料庫有多個儲存區,而且它的非同步 API 和搜尋索引可提供效能優勢。

IndexedDB 受所有平台上底層 WebView 的支援,但 browser 平台存在已知的限制。

網頁瀏覽器限制

實際行為可能取決於使用的瀏覽器。例如,Safari 和 Firefox 瀏覽器上的行為可能會有所不同。

使用摘要

  • IndexedDB 以非同步方式工作 - 您請求特定的資料庫操作,然後透過 DOM 事件收到結果通知。
  • 當您發出請求時,您會獲得一個請求物件,該物件提供 onerroronsuccess 事件,以及 resulterrorreadyState 等屬性。

以下程式碼片段示範 IndexedDB 的一些簡單用法

var db;
var databaseName = 'myDB';
var databaseVersion = 1;
var openRequest = window.indexedDB.open(databaseName, databaseVersion);
openRequest.onerror = function (event) {
    console.log(openRequest.errorCode);
};
openRequest.onsuccess = function (event) {
    // Database is open and initialized - we're good to proceed.
    db = openRequest.result;
    displayData();
};
openRequest.onupgradeneeded = function (event) {
    // This is either a newly created database, or a new version number
    // has been submitted to the open() call.
    var db = event.target.result;
    db.onerror = function () {
        console.log(db.errorCode);
    };

    // Create an object store and indexes. A key is a data value used to organize
    // and retrieve values in the object store. The keyPath option identifies where
    // the key is stored. If a key path is specified, the store can only contain
    // JavaScript objects, and each object stored must have a property with the
    // same name as the key path (unless the autoIncrement option is true).
    var store = db.createObjectStore('customers', { keyPath: 'customerId' });

    // Define the indexes we want to use. Objects we add to the store don't need
    // to contain these properties, but they will only appear in the specified
    // index of they do.
    //
    // syntax: store.createIndex(indexName, keyPath[, parameters]);
    //
    // All these values could have duplicates, so set unique to false
    store.createIndex('firstName', 'firstName', { unique: false });
    store.createIndex('lastName', 'lastName', { unique: false });
    store.createIndex('street', 'street', { unique: false });
    store.createIndex('city', 'city', { unique: false });
    store.createIndex('zipCode', 'zipCode', { unique: false });
    store.createIndex('country', 'country', { unique: false });

    // Once the store is created, populate it
    store.transaction.oncomplete = function (event) {
        // The transaction method takes an array of the names of object stores
        // and indexes that will be in the scope of the transaction (or a single
        // string to access a single object store). The transaction will be
        // read-only unless the optional 'readwrite' parameter is specified.
        // It returns a transaction object, which provides an objectStore method
        // to access one of the object stores that are in the scope of this
        //transaction.
        var customerStore = db.transaction('customers', 'readwrite').objectStore('customers');
        customers.forEach(function (customer) {
            customerStore.add(customer);
        });
    };
};

function displayData() {
}

如需更多資訊,請參閱

優點

  • 效能良好 - 非同步 API 不會阻礙 UI,而且索引可提供良好的搜尋效能。
  • 比 SQL 更容易學習的簡單資料模型。
  • 比 WebSQL 更具彈性的結構。
  • 多個資料庫和物件儲存區比 LocalStorage 提供更多結構。
  • 使用交易式資料庫模型可獲得穩健性。
  • 支援版本控制。

缺點

  • 具有巢狀回呼的複雜 API。
  • 總儲存量有限且可能被清除 如 MDN 所述

基於外掛程式的選項

FileSystem API

FileSystem API 是 Chrome 實作的 W3C 規格,但其他瀏覽器沒有實作。它提供在本地檔案系統上儲存和檢索資料的 API,並在優秀的 html5rocks 文章 中詳細描述。雖然任何 Cordova 平台都不原生支援該 API,但 File 外掛程式 提供了在所有 Cordova 平台上都可用的廣泛實作。

SQLite 外掛程式

SQLite 外掛程式提供的 API 與上述 WebSQL 幾乎相同。主要差異如下

  • 它可用於 Windows 平台。
  • 它實際上沒有大小限制。

它有以下變體

  • cordova-sqlite-storage - 核心版本,包含其自己的 sqlite3 實作。它支援 iOS、Android 和 Windows 平台。
  • cordova-sqlite-ext - 擴展版本,包含其他功能,包括 Android 和 iOS 上的 REGEXP 支援。
  • cordova-sqlite-evfree - 與 cordova-sqlite-ext 類似,但具有改進的記憶體處理能力。以 GPL v3 或商業許可證提供。

其他外掛程式

搜尋 Cordova 外掛程式,尋找提供其他儲存選項的外掛程式。