Write text in file in your extension's folder

By xngo on February 22, 2019

Below is a code sample showing how to write text in file(data.txt) in your extension's folder.

Note:

  • You need to change the value of var id variable to match the id of your extension.
  • The code below doesn't write correctly non-ASCII characters. If you need to write non-ASCII, see Writing_textual_data.
  • The location of the file created is stored in file.path. You can use alert(file.path); to view the location.
  • Each time you reinstall/update your extension, your extension's folder will be deleted. Therefore, your saved file in there is also deleted. It is not safe to save data in your extension's folder.
/*
 * Get the path of your extension's folder.
 */
var id  = "youExtId@openwritings.net";// The extension's id from install.rdf(i.e. <em:id>)
var ext = Components.classes["@mozilla.org/extensions/manager;1"]
                    .getService(Components.interfaces.nsIExtensionManager)
                    .getInstallLocation(id)
                    .getItemLocation(id);
 
/*
 * Setting up the full path of the file.
 */
var file = Components.classes["@mozilla.org/file/local;1"]
                     .createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(ext.path);  // The path passed to initWithPath() should be in "native" form.
file.append("data.txt");      // Use append() so you don't have to handle folder separator(e.g. / or \).
 
/*
 * Writing data to the file.
 */
var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
                         .createInstance(Components.interfaces.nsIFileOutputStream);
 
// See https://developer.mozilla.org/en/PR_Open#Parameters for the description of each octal constant.
foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0); 
var data = "text to write in the file.";
foStream.write(data, data.length);
foStream.close();

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.