Monday, June 3, 2024
141
rated 0 times [  144] [ 3]  / answers: 1 / hits: 129001  / 11 Years ago, thu, october 31, 2013, 12:00:00

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();
});
}

More From » firefox-addon

 Answers
2

Ah, you're using the SDK, I gather when re-reading the actual error of your other question.




  • You need to import TextEncoder explicitly from some other module, as SDK modules lack the class.

  • You need to 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.

  • You 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);

[#74602] Tuesday, October 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranav

Total Points: 693
Total Questions: 119
Total Answers: 119

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
pranav questions
Thu, Feb 10, 22, 00:00, 2 Years ago
Tue, Dec 28, 21, 00:00, 2 Years ago
Mon, Sep 6, 21, 00:00, 3 Years ago
Mon, Mar 8, 21, 00:00, 3 Years ago
;