The first part of the code basically needs to find the extensions file path. To most, this is within the mozilla profile folder. This is needed if you want to keep the file in the same folder as your extension. Otherwise, you could leave it out or give it a different file path. Id is used to hold the id of my extension.
//get extensions file path
const id = "sample@foo.net";
var extension = Components.classes["@mozilla.org/extensions/manager;1"]
.getService(Components.interfaces.nsIExtensionManager)
.getInstallLocation(id)
.getItemLocation(id);
The second part of the code is used to check whether or not you have the proper permissions to write a file to the local machine. I have not thoroughly tested this though.
try
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch (e)
{
alert("Permission to write to file was denied.");
}
Next, I create a variable to hold my file path (just easier for me); this is done using the extension path that we found earlier. Then create the proper components needed to write the file. First we need nsILocalFile, which to my understanding is like creating an instance of a file object. This needs a path which is basically the filepath I created. Then you need to create it.
//create proper path for xml file
var theFile = extension.path + "\\" + "metrics.xml";
//create component for file writing
var file = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath( theFile );
if(file.exists() == false) //check to see if file exists
{
alert("creating file...");
file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420);
}
Now, we create an output stream; nsIFileOutputStream, and give it the proper modes. As shown in my comments, I have chosen to do only write, create file if not exists, and truncate which basically deletes the content (leave this out and add 0x10 if you want to append to a file).
Then, you write to the file; giving the content and the length of the content, and close close the stream.
//create file output stream and use write/create/truncate mode
//0x02 writing, 0x08 create file, 0x20 truncate length if exist
var stream = Components.classes["@mozilla.org/network/file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);
//write data to file then close output stream
var content = this.xmldoc;
stream.write(content, content.length);
stream.close();
For more information on File I/O you can find it at
Mozilla Developer Center
Also check out the XPCOM reference at XUL Planet
. This is basically where I go to research each component used.
1 comments:
A little late now, but there is already some javascript objects to help with reading/writing to files called scriptable-io if you want to check it out.
Post a Comment