Managing files in your FF extension Directory


Below are the code snippets that I used to manipulate files in FF extension using XPCom. Hope these will be helpful to you. As I worked on Binary data so these snippets are capable of handling binary data as well as simple text data.

Getting path of your extension directory

var getWorkingDir= Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("UChrm", Components.interfaces.nsIFile);

var currPath = getWorkingDir.path.substr(0, getWorkingDir.path.lastIndexOf('\\'));
currPath += '\\extensions\\extensionname\\chrome\\content\\';

Create a file and copy data to it

var inputFile = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
inputFile.initWithPath( currPath +  'files\\' + randomNum + 'input.bin');

var stream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(inputFile, 0x04 | 0x08 | 0x20, 0600, 0); // write, create, truncate

stream.write(someData, someData.length);

if (stream instanceof Components.interfaces.nsISafeOutputStream) {
 stream.finish();
} else {
 stream.close();
}

Run a Executable file

// create an nsILocalFile for the executable
var file = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);

file.initWithPath(currPath + "program.exe");
// create an nsIProcess
var process = Components.classes["@mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess);

process.init(file);

var args = ["-arg1", "arg2"];
process.run(true, args, args.length);

Copy the data to file

var outputFile = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);

outputFile.initWithPath( currPath +  'files\\' + randomNum + 'output.bin');

var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);
istream.init(outputFile, 0x04 | 0x08, 0664, 0);

var bstream = Components.classes["@mozilla.org/binaryinputstream;1"].
createInstance(Components.interfaces.nsIBinaryInputStream);
bstream.setInputStream(istream);

var bytes = bstream.readBytes(bstream.available());
Advertisements

I am a web developer working @ Gaditek

Tagged with:
Posted in Browser Extension Development, Computer And Internet, Programming & Development

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: