Caret/js/file.js

92 lines
2.2 KiB
JavaScript
Raw Normal View History

2013-08-20 00:53:03 +00:00
define(function() {
/*
Unfortunately, mimicking Node isn't really feasible given the Chrome OS security model, but we still don't want to deal with the annoying Chrome filesystem APIs. This module wraps those in a more usable File object.
We should make
*/
var File = function() {
this.entry = null;
};
File.prototype = {
open: function(mode, c) {
var self = this;
if (typeof mode == "function") {
c = mode;
mode = "open";
}
//mode is "open" or "save"
var modes = {
"open": "openWritableFile",
"save": "saveFile"
};
chrome.fileSystem.chooseEntry({
type: modes[mode]
}, function(entry) {
2013-08-21 00:35:25 +00:00
if (!entry) return;
2013-08-20 00:53:03 +00:00
self.entry = entry;
c(self)
});
},
read: function(c) {
var reader = new FileReader();
reader.onload = function(data) {
c(null, reader.result);
};
reader.onerror = function(err) {
c(err, null);
};
this.entry.file(function(f) {
reader.readAsText(f);
});
},
write: function(data, options, c) {
var self = this;
this.entry.createWriter(function(writer) {
writer.onerror = function(err) {
c(err, self);
}
writer.onwriteend = function() {
//after truncation, actually write the file
writer.onwriteend = function() {
c(null, self);
}
var blob = new Blob(data);
writer.write(blob);
};
writer.trunctate(0);
});
},
stat: function(c) {
if (this.entry) {
return this.entry.file(function(f) {
c(null, f);
});
}
return c("No entry");
},
retain: function() {
return chrome.fileSystem.retainEntry(this.entry);
},
restore: function(id, c) {
var self = this;
chrome.fileSystem.isRestorable(id, function(is) {
if (is) {
chrome.fileSystem.restoreEntry(id, function(entry) {
self.entry = entry;
c(null, self);
});
} else {
c("Could not restore file");
}
});
}
};
return File;
});