我寫了一個Firefox擴展,用於從我的一位朋友開發的站點訪問書籤。在書籤服務關閉的情況下,我將書籤數據作爲JSON本地存儲在用戶的擴展配置文件目錄中的文本文件中。
我保存的書籤JSON功能是:
/**
* Stores bookmarks JSON to local persistence asynchronously.
*
* @param bookmarksJson The JSON to store
* @param fnSuccess The function to call upon success
* @param fnError The function to call upon error
*/
RyeboxChrome.saveBookmarkJson = function(bookmarksJson, fnSuccess, fnError) {
var cu = Components.utils;
cu.import("resource://gre/modules/NetUtil.jsm");
cu.import("resource://gre/modules/FileUtils.jsm");
var bookmarksJsonFile = RyeboxChrome.getOrCreateStorageDirectory();
bookmarksJsonFile.append("bookmarks.txt");
// You can also optionally pass a flags parameter here. It defaults to
// FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
var ostream = FileUtils.openSafeFileOutputStream(bookmarksJsonFile);
var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(bookmarksJson);
NetUtil.asyncCopy(istream, ostream, function(status) {
if (!Components.isSuccessCode(status) && typeof(fnError) === 'function') {
fnError();
} else if (typeof(fnSuccess) === 'function') {
fnSuccess();
}
return;
});
};
讀取數據的功能是:
/**
* Reads bookmarks JSON from local persistence asynchronously.
*
* @param fnSuccess Function to call when successful. The bookmarks JSON will
* be passed to this function.
*
* @param fnError Function to call upon failure.
*/
RyeboxChrome.getBookmarksJson = function(fnSuccess, fnError) {
Components.utils.import("resource://gre/modules/NetUtil.jsm");
var bookmarksJsonFile = RyeboxChrome.getOrCreateStorageDirectory();
bookmarksJsonFile.append("bookmarks.txt");
NetUtil.asyncFetch(bookmarksJsonFile, function(inputStream, status) {
if (!Components.isSuccessCode(status) && typeof(fnError) === 'function') {
fnError();
} else if (typeof(fnSuccess) === 'function'){
var data = NetUtil.readInputStreamToString(inputStream, inputStream.available());
fnSuccess(data);
}
});
};
最後,我getOrCreateStorageDirectory功能是:
/**
* Storage of data is done in a Ryebox directory within the user's profile
* directory.
*/
RyeboxChrome.getOrCreateStorageDirectory = function() {
var ci = Components.interfaces;
let directoryService = Components.classes["@mozilla.org/file/directory_service;1"].getService(ci.nsIProperties);
// Reference to the user's profile directory
let localDir = directoryService.get("ProfD", ci.nsIFile);
localDir.append("Ryebox");
if (!localDir.exists() || !localDir.isDirectory()) {
localDir.create(ci.nsIFile.DIRECTORY_TYPE, 0774);
}
return localDir;
};
難道我建議爲了存儲單個標誌?如果是這樣,oops:對於這種用例來說,這絕對是重量級的。順便說一下,現在正在討論針對此特定情況的解決方案:在dev.platform上的Gecko中存儲https://groups.google.com/d/topic/mozilla.dev.platform/vYbQqkqGzlo/discussion和https:/ /bugzilla.mozilla.org/show_bug.cgi?id=866238 – Nickolay 2013-05-01 01:36:35