This function sets up both a hard-coded file object and one that's got a relative path -- in this case, to the Desktop. (More on the choices for special, relative file locations here.)

Right now, it's hooked up to write out to a file called Output.txt on whatever your local OS believes is the desktop (or whatever it tells Firefox it believes is the desktop...). It's a simple task to swap out for the hard-coded file path if you'd rather.

This is working for me in Firefox 4.0. Paste it into the top of whatever js file you've got in chrome and call away with

writeToFile("This is what you'll be writing to a file.").

Got it? Here's the code.

// various sources for portions of this came from...
//http://jsdoodnauth.wordpress.com/2008/11/26/xul-file-io-write-files/
//https://developer.mozilla.org/en/Code_snippets/File_I%2f%2fO
//http://forums.mozillazine.org/viewtopic.php?f=19&p=10253261
function writeToFile(strTextToWrite) {

//===================================
// if you don't want to hard-code,
// blast from here...
//===================================
var strOutFilePath = "~/out.txt"; // this is Mac OS X-ese here.
// strOutFilePath = "C:\\out.txt"; // this is more Windows-y
var outFile = Components.classes["@mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
outFile.initWithPath(strOutFilePath);
alert("file path: " + strOutFilePath);
if ( outFile.exists() == false ) {
alert("File does not exist, " +
"but that shouldn't matter now, I think");
}
//===================================
// to here
//===================================



//===================================
// create a relative path
//===================================
// should be the desktop, even cross platform
var fileOnDesk = Components.classes["@mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("Desk", Components.interfaces.nsIFile);
// append to that crossplatform file (a folder) a specific doc name
fileOnDesk.append('Output.txt');
if (!fileOnDesk.exists()) {
fileOnDesk.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0666);
}
// 666 = 400+200+40+20+4+2 = r/w owner, groups, others


//===================================


var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);

strTextToWrite += "\n";
// to use the hard-coded outFile, swap fileOnDesk out for outFile
foStream.init(fileOnDesk, 0x02 | 0x08 | 0x10, 00666, 0);
foStream.write(strTextToWrite, strTextToWrite.length);
foStream.close();
}

Labels: , , ,