NetUtil.jsm

The NetUtil.jsm JavaScript code module provides easy-to-use APIs for performing common network related tasks.

To use these utilities, you first need to import the code module into your JavaScript scope:

Components.utils.import("resource://gre/modules/NetUtil.jsm");

Once you've imported the module, you can then use its methods.

Method overview

nsIAsyncStreamCopier asyncCopy(nsIInputStream aSource, nsIOutputStream aSink, [optional] aCallback)
void asyncFetch(aSource, aCallback)
nsIChannel newChannel(aWhatToLoad, [optional] aOriginCharset, [optional] nsIURI aBaseURI)
nsIURI newURI(aTarget, [optional] aOriginCharset, [optional] nsIURI aBaseURI)
String readInputStreamToString(aInputStream, aCount, aOptions)

Attributes

Attribute Type Description
ioService nsIIOService Returns a reference to nsIIOService.

Methods

asyncCopy()

The asyncCopy() method performs a simple asynchronous copy of data from a source input stream to a destination output stream. Both streams are automatically closed when the copy operation is completed.

nsIAsyncStreamCopier asyncCopy(
  aSource,
  aSink,
  aCallback
); 
Parameters
aSource
The input stream from which to read the source data. This must be an nsIInputStream based object.
aSink
The output stream to which to copy the data. This must be an nsIOutputStream based object.
aCallback
An optional function that will be called when the copy operation is completed. The callback receives a single parameter: the nsresult status code for the copy operation.
Return value

Returns the nsIAsyncStreamCopier object that is handling the copy.

Exceptions thrown

This method throws an exception with the message "Must have a source and a sink" if either aSource or aSink is null.

Example

This example writes a string to a file; it comes from the test suite for the NetUtil module.

var file = Cc["@mozilla.org/file/directory_service;1"].
           getService(Ci.nsIProperties).
           get("TmpD", Ci.nsIFile);
file.append("test-file.tmp");
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0666);
// Then, we need an output stream to our output file.
var ostream = Cc["@mozilla.org/network/file-output-stream;1"].
              createInstance(Ci.nsIFileOutputStream);
ostream.init(file, -1, -1, 0);
// Finally, we need an input stream to take data from.
const TEST_DATA = "this is a test string";
let istream = Cc["@mozilla.org/io/string-input-stream;1"].
              createInstance(Ci.nsIStringInputStream);
istream.setData(TEST_DATA, TEST_DATA.length);
NetUtil.asyncCopy(istream, ostream, function(aResult) {
  if (!Components.isSuccessCode(aResult)) {
    // an error occurred!
  }
})

asyncFetch()

The asyncFetch() method opens an input source, asynchronously, and gives an nsIInputStream containing the data obtained to the callback provided. The callback may then consume data from the input stream passed to the callback.

Note: Prior to Gecko 2.0, the input source was required to be specified as an nsIChannel.

Note: Support for specifying an nsIInputStream as the input source was added in Gecko 5.0.

asyncFetch(
  aSource,
  aCallback
); 
Parameters
aSource
The source to open asynchronously. This may be specified as an nsIURI, nsIFile, nsIChannel, nsIInputStream or as a string specifying the URL to open.
aCallback
A function that will be called when the open operation is completed. The callback receives three parameters: the input stream containing the data, if any (implementing nsIInputStream), an nsresult status code for the open operation, and a reference to the nsIRequest object.
Exceptions thrown

This method throws an exception with the message "Must have a source and a callback" if either aSource or aCallback is null.

Example

This example shows the basic code consumers would need to implement to be correct.

NetUtil.asyncFetch(channel, function(aInputStream, aResult) {
  // Check that we had success.
  if (!Components.isSuccessCode(aResult)) {
    // Handle error
    return;
  }
  // Consume the input stream.
});
Remarks
Note: If you specify an nsIChannel as the input source, and its notification callbacks have already been set, callers are responsible for implementing nsIBadCertListener and nsISSLErrorListener.

Requires Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)

newChannel()

Creates a new channel for the specified URI string, nsIURI, or nsIFile.

nsIChannel newChannel(
  aWhatToLoad,
  [optional] aOriginCharset,
  [optional] aBaseURI
); 
Parameters
Return value

An nsIChannel allowing access to the specified data source.

aWhatToLoad
A string specifying a URI, or an nsIURI or nsIFile object. The returned method will allow access to the specified data.
aOriginCharset
The optional character set to use when interpreting aWhatToLoad as a string; this is ignored if aWhatToLoad is not a string. Defaults to UTF-8 if not provided.
aBaseURI
The base URI for the spec, specified as an nsIURI. Only used if aWhatToLoad is a string.

newURI()

The newURI() method creates a new nsIURI. This method wraps the nsIIOService.newURI().

Note: Starting in Gecko 2.0, this method supports specifying an nsIFile as the target of the URI. In previous versions of Gecko, you must use a string to specify the URI.

nsIURI newURI(
  aTarget,
  [optional] aOriginCharset,
  [optional] aBaseURI
); 
Parameters
aTarget
Specifies the target of the URI as either a URI string or (starting in Gecko 2.0) as an nsIFile.
aOriginCharset
The optional character set for the URI. Defaults to UTF-8 if not provided.
aBaseURI
The base URI for the spec, specified as an nsIURI.
Return value

Returns the nsIURI object representing the specified target.

Exceptions thrown

This method throws an exception with the message "Must have a non-null string spec or nsIFile object" and result code NS_ERROR_INVALID_ARG if aSpec is null.

Requires Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)

readInputStreamToString()

Reads a given number of bytes from an input stream, returning a string containing those bytes. This works even if some of those bytes are zeros, instead of terminating the string at the first zero byte.

String readInputStreamToString(
  aInputStream,
  aCount,
  aOptions
);
Parameters
aInputStream
The input stream from which to read the data.
aCount
The number of bytes to read from the stream. You can call nsIInputStream.available() to get the number of bytes currently available.
aOptions
Specifies additional options to control the reading process. This is a JavaScript object with fields as specified in Options.
Options

The aOptions parameter is a JavaScript object which can have any or all of the following fields:

Field name Description
charset The character encoding to use when interpreting the input stream. If you don't provide this, the input won't be decoded at all and the raw bytes will be returned.
replacement A character with which to replace any invalid byte sequences in the input stream. If you don't specify a replacement character, any invalid sequences will result in NS_ERROR_ILLEGAL_INPUT being thrown. This option only has effect if charset is as well.
Return value

A string containing the bytes read from the input stream.

Exceptions thrown
NS_ERROR_INVALID_ARG
The specified stream is not an nsIInputStream.
NS_BASE_STREAM_WOULD_BLOCK
Reading from the specified stream would block the calling thread, and the stream is in non-blocking mode.
NS_ERROR_FAILURE
There aren't at least aCount bytes available to read from the stream.
NS_ERROR_ILLEGAL_INPUT
The input stream has invalid byte sequences, and no replacement character was specified using aOptions.replacement.

See also

Document Tags and Contributors

 Last updated by: Nmaier,