Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
XPCOM File I/O
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