Ehsan
Ehsan

Reputation: 4464

Firefox Extension Write data to File

I have a hashTable like data set in my Firefox extension, and I am willing to save that in a simple text file. I have been going through a lot of sample codes but none of those are working for me. For example, 1, 2. I am a beginner in developing extensions on Firefox, and it seems to me the syntax for writing to a file is a bit complicated. Can anyone give me a working example? BTW, I am using unix. Because I saw example for writing to a file that they were using windows system calls.

Upvotes: 2

Views: 4533

Answers (2)

diegocr
diegocr

Reputation: 1000

This is the easier and straight forward way:

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] : https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView

[2] : https://developer.mozilla.org/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread#OS.File.writeAtomic%28%29

Upvotes: 1

ekcr1
ekcr1

Reputation: 4514

Here's some example code to write a file called myfile.txt to your firefox profile directory:

    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();

If you are using the Firefox Addon SDK (jetpack), you'll need to modify it a bit.

    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();

Upvotes: 1

Related Questions