Recently, a few bugs have landed enabling a bunch of nice things for consumers of NetUtil.jsm:
- NetUtil.newURI can take a string (plus optional character set and base URI) or an nsIFile.
- A new method for creating channels has been created. NetUtil.newChannel can take an nsIURI, a string (plus optional character set and base URI), or an nsIFile.
- NetUtil.asyncFetch can take an nsIChannel, an nsIURI, a string (plus optional character set and base URI), or an nsIFile.
This means, among other things, that it now requires less code to read a file asynchronously than it does synchronously. The old way to do this asynchronously can be seen here on MDC. This would give the consumer a byte array of the data in the file. Compared to the synchronous case, which can be seen here. Both are pretty verbose and clunky to use. The new way looks like this:
NetUtil.asyncFetch(file, function(aInputStream, aResult) {
if (!Components.isSuccessCode(aResult)) {
// Handle Error
return;
}
// Consume input stream
});
One function call, with a callback passed in. There is a slight difference from the old asynchronous method, however. NetUtil.asyncFetch gives the consumer an nsIInputStream instead of a byte array. The input stream is a bit more useful than a raw byte array, although it can be painful to use in JavaScript at times (maybe we need an easy method to convert an input stream to a string?). I look forward to patches using this method to read files instead of doing it synchronously.
7 replies on “NetUtil.jsm Just Got More Useful”
http://hg.mozilla.org/mozilla-central/rev/6453f3ca39fc
\o/
Thank you, Shawn. Too bad that all these changes landed only for 1.9.3 – meaning that it will most likely take two years until I can start using that module.
Should we back-port them? They look additive.
We should be able to. We haven’t been willing to do that in the past, so I didn’t bother requesting it. Fully tested too, so we’ll know if it works or not.
Mike, I am not sure whether this is a good idea. Having a feature supported in 3.6.2 but not 3.6.1 might confuse extension developers – if it works in most recent 3.6 nobody will verify that it works in older 3.6 releases as well. As a result we might get extensions with wrong compatibility range. While these additions are nice, they aren’t really essential, so maybe better wait for 3.7 (and sure, it sucks to write code that nobody will use for at least half a year).
I don’t think that’s much of a problem — easy to catch and deal with, and most users (esp, IMO, those who install add-ons) are updated anyway. We can document it explicitly, too.
Yes, I also thought that people using add-ons are using up-to-date Firefox versions – until I discovered that quite a few of them don’t and you will get bug reports if you specify minVersion as 3.0.11 rather than 3.0.12. And documentation will also get you only so far, many add-on authors don’t seem to read any documentation whatsoever.