当我尝试同步读取文件时,Firefox会冻结。 当我尝试异步读取文件时,我得到数字而不是单词。
此代码段...
var MY_ID = "cbdeltrem1984@bol.com.br";
var em = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);
var file = em.getInstallLocation(MY_ID).getItemFile(MY_ID, "wordlist.txt");
...加上此代码段...
var appInfo=Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
var isOnBranch = appInfo.platformVersion.indexOf("1.8") == 0;
var ios=Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var fileURI=ios.newFileURI(file);
var channel = ios.newChannelFromURI(fileURI);
var observer = {
onStreamComplete : function(aLoader, aContext, aStatus, aLength, aResult) {
alert(aResult);
}
};
var sl = Components.classes["@mozilla.org/network/stream-loader;1"].createInstance(Components.interfaces.nsIStreamLoader);
if (isOnBranch) {
sl.init(channel, observer, null);
} else {
sl.init(observer);
channel.asyncOpen(sl, channel);
}
...警告数字而非单词。
如何逐行异步读取文件?
答案 0 :(得分:0)
以下示例可以异步读取文件,而无需锁定UI线程(仅适用于FF4 +,因为我使用了模块)。不逐行阅读...另外,我认为它是文本文件,但是..
Components.utils.import("resource://gre/modules/NetUtil.jsm");
NetUtil.asyncFetch(file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
// Handle error!
return;
}
// The file data is contained within inputStream.
// You can read it into a string with
var data = NetUtil.readInputStreamToString(inputStream, inputStream.available());
Components.utils.reportError("data:" + data);
});
来源: