Javascript Firefox扩展将数据写入文件

Javascript Firefox扩展将数据写入文件,javascript,firefox,Javascript,Firefox,我的Firefox扩展中有一个类似哈希表的数据集,我愿意将其保存在一个简单的文本文件中。我已经阅读了很多示例代码,但没有一个对我有用。例如我是在Firefox上开发扩展的初学者,在我看来,写入文件的语法有点复杂。谁能给我举个有效的例子?顺便说一句,我正在使用unix。因为我看到了使用windows系统调用写入文件的示例。以下是一些示例代码,用于将名为myfile.txt的文件写入firefox配置文件目录: var txt = "my file contents"; var f

我的Firefox扩展中有一个类似哈希表的数据集,我愿意将其保存在一个简单的文本文件中。我已经阅读了很多示例代码,但没有一个对我有用。例如我是在Firefox上开发扩展的初学者,在我看来,写入文件的语法有点复杂。谁能给我举个有效的例子?顺便说一句,我正在使用unix。因为我看到了使用windows系统调用写入文件的示例。

以下是一些示例代码,用于将名为myfile.txt的文件写入firefox配置文件目录:

    var txt = "my file contents";

    var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD",  Components.interfaces.nsIFile);
    file.append("myfile.txt");
    var fs = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
    fs.init(file, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate
    fs.write(txt, txt.length);
    fs.close();
如果您使用的是Firefox插件SDK(jetpack),则需要对其进行一些修改

    var {Cc, Ci} = require("chrome");

    var txt = "my file contents";

    var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
    file.append("myfile.txt");
    var fs = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
    fs.init(file, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate
    fs.write(txt, txt.length);
    fs.close();

这是更简单、更直接的方法:

Components.utils.import("resource://gre/modules/osfile.jsm");

// Saving the pointed filename into your Firefox profile
let whereToSave = OS.Path.join(OS.Constants.Path.profileDir, "YOUR-FILENAME.txt");

// Convert your "hash table" to a Typed Array[1]
let dataToSave = hashTableAsArrayBufferView;

// Check MDN[2] for writeAtomic() details
OS.File.writeAtomic(whereToSave, dataToSave).then(function(aResult) {
    // Write operation finished
    ...
}, Components.utils.reportError);
[1] :


[2] :

您能否提供一些代码示例,看看错误控制台中是否记录了任何错误?