async line-by-line file reading
When I try to read a file synchronously, Firefox freezes. When I try to read a file asynchronously, I get numbers instead of words.
This code snippet...
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");
...plus this code snippet...
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);
}
...alerts numbers instead of words.
How to read a file asynchronously line-by-line?
The below sample can read files asynchronously, without locking UI thread (works with FF4+ only though, since I used Modules). Doesn't read line-by-line... Also, I assumed it to be text file, though..
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);
});
Sources:
- https://developer.mozilla.org/en/JavaScript_code_modules/NetUtil.jsm
- https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO#Read_into_a_stream_or_a_string
精彩评论