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.