Firefox Extension Javascript Access Local File

Based on a MDN page, this code snippet writes “data” into a file named “data.txt” in the firefox profile directory. (More snippets are on a separate page).


// get the "data.txt" file in the profile directory
var file = FileUtils.getFile("ProfD", ["data.txt"]);

// file is nsIFile, data is a string

// You can also optionally pass a flags parameter here. It defaults to
var ostream = FileUtils.openSafeFileOutputStream(file)

var converter = Components.classes[""].
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);

// The last argument (the callback) is optional.
NetUtil.asyncCopy(istream, ostream, function(status) {
  if (!Components.isSuccessCode(status)) {
    // Handle error!

  // Data has been written to the file.

Replace ProfD by DefProfRt for profile root (e.g. ~/.mozilla/firefox), or Home for user’s home, etc. Refer to the MDN doc.


About minghuasweblog

a long time coder
This entry was posted in All, Mozilla Firefox and Thunderbird and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s