本文介绍了ReferenceError:TextEncoder未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Firefox上写了一个简单的插件 - 24,在Linux上。我得到这个错误:
$ $ $ $ $ $ $ $ $ $ $ b $ Reference $
当我这样做时:var encoder = new TextEncoder();
我正在使用的函数是:
pre $函数write_text(文件名,文本){
var编码器= new TextEncoder();
var data = encoder.encode(text);
Task.spawn(function(){
let pfh = OS.File.open(/ tmp / foo,{append:true});
yield pfh.write(text) ;
产生pfh.flush();
产生pfh.close();
});
解决方案
在重新读取其他问题的实际错误时,我收集了SDK。
$ b $ ul
这是我在Firefox 25中测试的一个完整的工作示例( main.js )
const {Cu} = require(chrome);
//使用Cu.import()
加载TextEncoder是很重要的//你不能用| 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);
产生file.close();
console.log(写入,文件名);
})。
}
write_text(foo,some text);
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.
- 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");
这篇关于ReferenceError:TextEncoder未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!