2

I'm using xul to code a firefox extension, so I need to read/write from local file. How to create for example file "temp.txt" in the following directory "c:/data" ?

Ashraf Bashir
  • 9,686
  • 15
  • 57
  • 82

3 Answers3

6

XUL is a mark-up language, you use it to create a user interface. To do things like writing to files you would use XPCOM. Everything else can be found in the documentation:

General documentation: FileUtils.jsm, NetUtil.jsm, File I/O code snippets

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
5

I found the solution for those who are interested:

getLocalDirectory : function() { 
    let directoryService = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties); 
    let localDir = directoryService.get("ProfD", Ci.nsIFile); 
    localDir.append("FolderName"); 
    if (!localDir.exists() || !localDir.isDirectory())  
        localDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0774); 
    return localDir; 
}, 

writeFile: function(data) {
    let myFile = lbbs.files.getLocalDirectory(); 
    myFile.append("FileName.txt"); 
    if ( myFile.exists() == false ) 
         myFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0774); 
    Components.utils.import("resource://gre/modules/NetUtil.jsm"); 
    Components.utils.import("resource://gre/modules/FileUtils.jsm"); 
    var ostream = FileUtils.openSafeFileOutputStream(myFile) 
    var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]. 
    createInstance(Components.interfaces.nsIScriptableUnicodeConverter); 
    converter.charset = "UTF-8"; 
    var istream = converter.convertToInputStream(data); 
    NetUtil.asyncCopy(istream, ostream, function(status) { 
        if (!Components.isSuccessCode(status))  
            return; 
    });
},

readFile: function() {
    let myFile = lbbs.files.getLocalDirectory(); 
    myFile.append("FileName.txt"); 
    if (myFile.exists() == false) 
        myFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0774); 
    var data = ""; 
    var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream); 
    var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].createInstance(Components.interfaces.nsIConverterInputStream); 
    fstream.init(myFile, -1, 0, 0); 
    cstream.init(fstream, "UTF-8", 0, 0); 
    let (str = {}) { 
        let read = 0; 
        do { 
            read = cstream.readString(0xffffffff, str); 
            data += str.value; 
        } while (read != 0); 
    } 
    cstream.close();  
    return data; 
},


The file is now created in: %USER_PROFILE%\AppData\Roaming\Mozilla\FireFox\Profiles\aamu4bzq.default\FolderName\FileName.txt

Ashraf Bashir
  • 9,686
  • 15
  • 57
  • 82
1

I think there will be problem when creating the folder outside the application base directory.
For example :- if you want to create a folder inside C:\TEMP it may fail

user1226320
  • 413
  • 1
  • 4
  • 11