Created
August 23, 2012 09:36
-
-
Save anantn/3434708 to your computer and use it in GitHub Desktop.
XPCOM File I/O
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {classes: Cc, interfaces: Ci, utils: Cu} = Components; | |
Cu.import("resource://gre/modules/NetUtil.jsm"); | |
// Let's enumerate all available files in ~ | |
function getHomeDir() { | |
let home = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile); | |
home.initWithPath("~"); | |
if (!home.isDirectory()) { | |
alert("that seems wrong..."); | |
return; | |
} | |
return home.directoryEntries; | |
} | |
// Read a text/plain file into a string | |
function readFile(file, cb) { | |
alert("reading " + file.path); | |
let channel = NetUtil.newChannel(file); | |
channel.contentType = "text/plain"; | |
NetUtil.asyncFetch(file, function(is, result) { | |
if (!Components.isSuccessCode(status)) { | |
cb("error while reading..."); | |
return; | |
} | |
let data = | |
NetUtil.readInputStreamToString(is, is.available()); | |
is.close(); | |
cb(data); | |
}); | |
} | |
// Opening and reading the first file in ~ | |
let files = []; | |
let homedir = getHomeDir(); | |
while (homedir.hasMoreElements()) { | |
let file = homedir.getNext().QueryInterface(Ci.nsIFile); | |
if (!file.isDirectory()) { | |
files.push(file); | |
} | |
} | |
readFile(files[0], function(a) { alert(a); } ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment