Append data to file with firefox extension

我与影子孤独终老i 提交于 2019-12-11 02:13:44

问题


I'm trying to build a firefox extension and i want to write things periodically in a file. So i want a file in which i append new strings. The following code writes the file but at the end the file contains only the last string i wrote and not the previous.

Can you help me?

mydir=null;
mylog=null;
mystream=null;

function initFolder() {
var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
           .getService(Components.interfaces.nsIProperties);
 mydir = dirSvc.get("ProfD", Components.interfaces.nsILocalFile);
 mydir.append("mylogFolder");
 if (!mydir.exists())
    mydir.create(mydir.DIRECTORY_TYPE, 0700);

 var fileName = "logFile.txt";
 mylog = mydir.clone();
 mylog.append(fileName);
 mylog.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0777);
}

function mywriteFile(aData) { 
  // init stream
  mystream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
             createInstance(Components.interfaces.nsIFileOutputStream);
  try {
    mystream.init(mylog, 0x02 | 0x10, 0777, 0); //these flags to append file?
  } catch (e) {
    dump("exception: " + e + "\n");
  }

  // convert to UTF-8
  var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
                createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
  converter.charset = "UTF-8";
  var convertedData = converter.ConvertFromUnicode(aData);
  convertedData += converter.Finish();
  try {
    mystream.write(convertedData, convertedData.length);
  } catch (e) {
dump("exception: " + e + "\n");
  }
}

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

window.addEventListener("load", function(){ initFolder(); }, false);
window.addEventListener("unload", function(){close(); }, false);

Any suggestions?


回答1:


The reason the "safe" file output stream is safe is that it writes the data to a temporary file and only copies it over to the actual file when you call stream.finish(). So any existing data is lost. If you want to append you'll have to use a different component (plain old "@mozilla.org/network/file-output-stream;1" should work fine).



来源:https://stackoverflow.com/questions/6892267/append-data-to-file-with-firefox-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!