Я написал расширение 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;
};