How to read and write to files?

Talk about add-ons and extension development.
Noitidart
Posts: 1168
Joined: September 16th, 2007, 8:01 am

Re: How to read and write to files?

Post by Noitidart »

TCaudillLG wrote:You think you've learned something from this thread, but trust me... when it comes time to actually implement this in your addon, you'll find you haven't learned very much. Biggest waste of time ever, the equivalent of trying to build a house on a swamp.

why so glum? search for my addon called XPICompiler on AMO, i implement this.

i feel you might have got there because you couldn't figure something out. post it up and ill help you out. its really quite easy, and the way i prefer is without the SDK, that way i have control over the overhead, i dont know what all the sdk does. for sure the file size comes out bigger because it has libraries.

but u can do sdk too ppl here know that too, i just cant help with that, my computers not good enough to set up the environemtn
lithopsian
Posts: 3664
Joined: September 15th, 2010, 9:03 am

Re: How to read and write to files?

Post by lithopsian »

Don't feed the trolls.
Noitidart
Posts: 1168
Joined: September 16th, 2007, 8:01 am

Re: How to read and write to files?

Post by Noitidart »

lithopsian wrote:Don't feed the trolls.

hahaha. im so gullible though man i believe in helping people because i got to where i am now by people helping me. but man that babylon person is extremely sour, they arent trying at all, i wrote the whole addon for them and they cant debug a bug thats in their own javascript lol. i cant spoon feed babylon any more lol.
tcaud
Posts: 19
Joined: February 1st, 2014, 3:49 pm

Re: How to read and write to files?

Post by tcaud »

There are plans to kill off non-SDK addons entirely. And since XULRunner is gonna be killed soon (again), that'll probably be sooner rather than later.
Noitidart
Posts: 1168
Joined: September 16th, 2007, 8:01 am

Re: How to read and write to files?

Post by Noitidart »

thats impossible. how would they go about doing that? even sdk addons use bootstrap method.
tcaud
Posts: 19
Joined: February 1st, 2014, 3:49 pm

Re: How to read and write to files?

Post by tcaud »

It's being replaced with a special mode of Firefox invoked with the "-app" switch. But yeah I was told last year SDK would replace XUL completely. My understanding is that even XUL is on its way out.
Noitidart
Posts: 1168
Joined: September 16th, 2007, 8:01 am

Re: How to read and write to files?

Post by Noitidart »

ah ok we're safe then. just restart needed addons are being discontinued by the sounds of it.
tcaud
Posts: 19
Joined: February 1st, 2014, 3:49 pm

Re: How to read and write to files?

Post by tcaud »

I'd go to Moz Chat and ask to make sure. The man in charge, canukistan, seems pretty serious about this. Also the hoops required for sharing variables are now equally as bad for XUL and SDK, now that shared namespaces have been eliminated. It's event listeners or bust...
Noitidart
Posts: 1168
Joined: September 16th, 2007, 8:01 am

Re: How to read and write to files?

Post by Noitidart »

It really sounds physically impossible but I'll check.

Also sharing variables is now easier then ever, and more efficient then ever. Do this:

Code: Select all

Cu.import('resource://gre/modules/XPCOMUtils.jsm');
var cServ = {};
XPCOMUtils.defineLazyGetter(cServ, 'zw', function () {
   return 'hiiiiiiiiiiiiii';
});


now you can access that from anywhere. you can even return a function if you want. you access it by importing cServ, im not sure how you do that though ill ask.
yajd
Posts: 55
Joined: February 3rd, 2014, 6:02 pm

Re: How to read and write to files?

Post by yajd »

hi all im trying to modify my overwrite function to appned to the file, can asyncCopy do this?

Code: Select all

function overwrite(nsiFile, data, callback) {
   //data is data you want to write to file
   //if file doesnt exist it is created
   var ostream = FileUtils.openSafeFileOutputStream(nsiFile)
 
  var converter = Cc['@mozilla.org/intl/scriptableunicodeconverter'].createInstance(Ci.nsIScriptableUnicodeConverter);
   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!
         Cu.reportError('error on write isSuccessCode = ' + status);
         return;
      }
      // Data has been written to the file.
      callback(status)
   });
}





my solution right now is to combine readFile and overwriteFile like this:

Code: Select all

Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");


//example
var logFile = FileUtils.getFile('Desk', ['rawr.txt']); //this gets file on desktop named 'rawr.txt'
appendFile(logFile, 'trala trala trala', function (status) {
    if (!Components.isSuccessCode(status)) {
        alert('appendFile failed');
    } else {
        alert('appendFiled SUCCESFUL');
    }
});

//end example



function appendFile(nsiFile, data, callback) {
    //callback is fed arg1 of status
    var afterRead = function(dataReadFromFile, status) {
        if (dataReadFromFile === null) {
            //file did not exist before so in overwrite it will make the file
            overwriteFile(nsiFile, data, afterWrite);
        } else {
            overwriteFile(nsiFile, dataReadFromFile + '\n' + data, afterWrite);
        }
    }
   
    var afterWrite = function (status) {
        if (callback) {
            callback(status);
        }
    }
   
    readFile(nsiFile, afterRead);

}

function overwriteFile(nsiFile, data, callback) {
   //data is data you want to write to file
   //if file doesnt exist it is created
   var ostream = FileUtils.openSafeFileOutputStream(nsiFile)
 
  var converter = Cc['@mozilla.org/intl/scriptableunicodeconverter'].createInstance(Ci.nsIScriptableUnicodeConverter);
   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!
         Cu.reportError('error on write isSuccessCode = ' + status);
         callback(status);
         return;
      }
      // Data has been written to the file.
      callback(status)
   });
}

function readFile(file, callback) {
   //you must pass a callback like function(dataReadFromFile, status) { }
   //then within the callback you can work with the contents of the file, it is held in dataReadFromFile
   //callback gets passed the data as string
   NetUtil.asyncFetch(file, function (inputStream, status) {
      //this function is callback that runs on completion of data reading
      if (!Components.isSuccessCode(status)) {
         Cu.reportError('error on file read isSuccessCode = ' + status);
         callback(null, status)
         return;
      }
      var data = NetUtil.readInputStreamToString(inputStream, inputStream.available());
      callback(data, status);
   });
}
Last edited by yajd on February 7th, 2014, 11:42 am, edited 1 time in total.
lithopsian
Posts: 3664
Joined: September 15th, 2010, 9:03 am

Re: How to read and write to files?

Post by lithopsian »

When you open the file you specify whether you want to append or truncate (or open readonly, writeonly, etc).
yajd
Posts: 55
Joined: February 3rd, 2014, 6:02 pm

Re: How to read and write to files?

Post by yajd »

Ah thanks litho!!!

I modified the function to this. It says write is succesful but it is overwriting even if i replace the truncate flag with append. :(

Code: Select all

function writeFile(nsiFile, data, overwrite, callback) {
    //overwrite is true false, if false then it appends
    //nsiFile must be nsiFile
    if (overwrite) {
        var openFlags = FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
    } else {
        var openFlags = FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_APPEND;
    }
   //data is data you want to write to file
   //if file doesnt exist it is created
   var ostream = FileUtils.openSafeFileOutputStream(nsiFile, openFlags)
 
  var converter = Cc['@mozilla.org/intl/scriptableunicodeconverter'].createInstance(Ci.nsIScriptableUnicodeConverter);
   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!
         Cu.reportError('error on write isSuccessCode = ' + status);
         callback(status);
         return;
      }
      // Data has been written to the file.
      callback(status)
   });
}
lithopsian
Posts: 3664
Joined: September 15th, 2010, 9:03 am

Re: How to read and write to files?

Post by lithopsian »

I don't think you can append in safe mode. Try with a regular file output stream.
yajd
Posts: 55
Joined: February 3rd, 2014, 6:02 pm

Re: How to read and write to files?

Post by yajd »

woohoo that fixed it!

for those who want a copy paste:

Code: Select all

function writeFile(nsiFile, data, overwrite, callback) {
    //overwrite is true false, if false then it appends
    //nsiFile must be nsiFile
    if (overwrite) {
        var openFlags = FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
    } else {
        var openFlags = FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_APPEND;
    }
   //data is data you want to write to file
   //if file doesnt exist it is created
   var ostream = FileUtils.openFileOutputStream(nsiFile, openFlags)
 
  var converter = Cc['@mozilla.org/intl/scriptableunicodeconverter'].createInstance(Ci.nsIScriptableUnicodeConverter);
   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!
         Cu.reportError('error on write isSuccessCode = ' + status);
         callback(status);
         return;
      }
      // Data has been written to the file.
      callback(status)
   });
}



Buttttt now I'm antsy I don't understand: mdn shows that openSafe takes flags as 2nd param. ill look it up on mxr see whats going on
whats the difference between openSafeFileOutputStream and just openFileOutputStream.

MDN just says it has some behavior flags. so if im setting openFlags to APPEND | CREATE | WRITE, it no longer has that bheavior flag right? so its equivalent to openSafe?

https://developer.mozilla.org/en-US/doc ... ream%28%29

https://developer.mozilla.org/en-US/doc ... ream%28%29


I also dont ever run closeFileOutputStream, is this ok? should i run it?
lithopsian
Posts: 3664
Joined: September 15th, 2010, 9:03 am

Re: How to read and write to files?

Post by lithopsian »

Safe file output creates a temporary file with your writes, then replaces the original file with it when you close (finish?) it. It makes sense that it wouldn't work with append although I haven't tested it or looked at the source to check. Some of the other flags will still work.
Post Reply