I'm writing a simple addon in Firefox - 24, on Linux. I get the error:
ReferenceError: TextEncoder is not defined
when I do: var encoder = new TextEncoder(); the function I'm using is:
function write_text(filename, text) {
var encoder = new TextEncoder();
var data = encoder.encode(text);
Task.spawn(function() {
let pfh = OS.File.open("/tmp/foo", {append: true});
yield pfh.write(text);
yield pfh.flush();
yield pfh.close();
});
}
Ah, you're using the SDK, I gather when re-reading the actual error of your other question.
TextEncoder
explicitly from some other module, as SDK modules lack the class.yield
OS.File.open.append:
is only supported in Firefox 27+.flush()
is only supported in Firefox 27+ (and a bad idea anyway). Use .writeAtomic
if you need that.write: true
to write to a file.Here is a full, working example I tested in Firefox 25 (main.js
)
const {Cu} = require("chrome");
// It is important to load TextEncoder like this using Cu.import()
// You cannot load it by just |Cu.import("resource://gre/modules/osfile.jsm");|
const {TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
const {Task} = Cu.import("resource://gre/modules/Task.jsm", {});
function write_text(filename, text) {
var encoder = new TextEncoder();
var data = encoder.encode(text);
filename = OS.Path.join(OS.Constants.Path.tmpDir, filename);
Task.spawn(function() {
let file = yield OS.File.open(filename, {write: true});
yield file.write(data);
yield file.close();
console.log("written to", filename);
}).then(null, function(e) console.error(e));
}
write_text("foo", "some text");