NetUtil.jsm

  • Revision slug: JavaScript_code_modules/NetUtil.jsm
  • Revision title: NetUtil.jsm
  • Revision id: 45665
  • Created:
  • Creator: Sheppy
  • Is current revision? No
  • Comment 8 words added, 17 words removed

Revision Content

{{ fx_minversion_header("3.6") }}

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

{{ interface("nsIAsyncStreamCopier") }} asyncCopy({{ interface("nsIInputStream") }} aSource, {{ interface("nsIOutputStream") }} aSink, [optional] aCallback)
{{ interface("nsIURI") }} newURI(aSpec, [optional] aOriginCharset, [optional] {{ interface("nsIURI") }} aBaseURI)
void asyncFetch(aSource, [optional] aCallback)

Attributes

Attribute Type Description
ioService nsIIOService Returns a reference to nsIIOService. {{ gecko_minversion_inline("1.9.3") }}

Methods

asyncCopy

The asyncCopy() method performs a simple asynchronous copy of data from a source input stream to a destination input 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 {{ interface("nsIInputStream") }} based object.
aSink
The output stream to which to copy the data. This must be an {{ interface("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 {{ interface("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 {{ interface("nsIInputStream") }} containing the data obtained to the callback provided. The callback may then consume data from the input stream passed to the callback.

{{ gecko_minversion_note("1.9.3", "Prior to Gecko 1.9.3, the input source was required to be specified as an nsIChannel.") }}

asyncFetch(
  aSource,
  aCallback
); 
Parameters
aSource
The source to open asynchronously. This may be specified as an {{ interface("nsIURI") }}, {{ interface("nsIFile") }}, {{ interface("nsIChannel") }}, 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 two parameters: the input stream containing the data (implementing {{ interface("nsIInputStream") }}) and the nsresult status code for the open operation.
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.
});

newURI

The newURI() method creates a new {{ interface("nsIURI") }}. This method wraps the {{ ifandmethod("nsIIOService", "newURI") }}.

nsIURI newURI(
  aSpec,
  [optinoal] aOriginCharset,
  [optional] aBaseURI
); 
Parameters
aSpec
The spec for the desired URI.
aOriginCharset
The optional character set for the URI. Defaults to UTF-8 if not provided.
aBaseURI
The base URI for the spec.
Return value

Returns the {{ interface("nsIURI") }} object representing aSpec.

Exceptions thrown

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

See also

Revision Source

<p>{{ fx_minversion_header("3.6") }}</p>
<p>The <code>NetUtil.jsm</code> JavaScript code module provides easy-to-use APIs for performing common network related tasks.</p>
<p>To use these utilities, you first need to import the code module into your JavaScript scope:</p>
<pre class="eval"><span class="nowiki">Components.utils.import("</span><a class=" external" href="resource://gre/modules/XPCOMUtils.jsm" rel="external nofollow" target="_blank" title="resource://gre/modules/XPCOMUtils.jsm"><span class="nowiki">resource://gre/modules/NetUtil.jsm</span></a><span class="nowiki">");</span>
</pre>
<p>Once you've imported the module, you can then use its methods.</p>
<h2 name="Method_overview">Method overview</h2>
<table class="standard-table"> <tbody> <tr> <td><code>{{ interface("nsIAsyncStreamCopier") }} asyncCopy({{ interface("nsIInputStream") }} aSource, {{ interface("nsIOutputStream") }} aSink, [optional] aCallback)</code></td> </tr> <tr> <td><code>{{ interface("nsIURI") }} newURI(aSpec, [optional] aOriginCharset, [optional] {{ interface("nsIURI") }} aBaseURI)</code></td> </tr> <tr> <td><code>void asyncFetch(aSource, [optional] aCallback)</code></td> </tr> </tbody>
</table>
<h2>Attributes</h2>
<table class="standard-table"> <tbody> <tr> <td class="header">Attribute</td> <td class="header">Type</td> <td class="header">Description</td> </tr> <tr> <td><code>ioService</code></td> <td><code>nsIIOService</code></td> <td>Returns a reference to nsIIOService. {{ gecko_minversion_inline("1.9.3") }}</td> </tr> </tbody>
</table>
<h2>Methods</h2>
<h3>asyncCopy</h3>
<p>The <code>asyncCopy()</code> method performs a simple asynchronous copy of data from a source input stream to a destination input stream. Both streams are automatically closed when the copy operation is completed.</p>
<pre>nsIAsyncStreamCopier asyncCopy(
  aSource,
  aSink,
  aCallback
); 
</pre>
<h6>Parameters</h6>
<dl> <dt><code>aSource</code></dt> <dd>The input stream from which to read the source data. This must be an {{ interface("nsIInputStream") }} based object.</dd> <dt><code>aSink</code></dt> <dd>The output stream to which to copy the data. This must be an {{ interface("nsIOutputStream") }} based object.</dd> <dt><code>aCallback</code></dt> <dd>An optional function that will be called when the copy operation is completed. The callback receives a single parameter: the <code>nsresult</code> status code for the copy operation.</dd>
</dl>
<h6>Return value</h6>
<p>Returns the {{ interface("nsIAsyncStreamCopier") }} object that is handling the copy.</p>
<h6>Exceptions thrown</h6>
<p>This method throws an exception with the message "Must have a source and a sink" if either <code>aSource</code> or <code>aSink</code> is null.</p>
<h4>Example</h4>
<p>This example writes a string to a file; it comes from the test suite for the NetUtil module.</p>
<pre class="brush: js">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!
  }
})
</pre>
<h3>asyncFetch</h3>
<p>The <code>asyncFetch()</code> method opens an input source, asynchronously, and gives an {{ interface("nsIInputStream") }} containing the data obtained to the callback provided. The callback may then consume data from the input stream passed to the callback.</p>
<p>{{ gecko_minversion_note("1.9.3", "Prior to Gecko 1.9.3, the input source was required to be specified as an <code>nsIChannel</code>.") }}</p>
<pre>asyncFetch(
  aSource,
  aCallback
); 
</pre>
<h6>Parameters</h6>
<dl> <dt><code>aSource</code></dt> <dd>The source to open asynchronously. This may be specified as an {{ interface("nsIURI") }}, {{ interface("nsIFile") }}, {{ interface("nsIChannel") }}, or as a string specifying the URL to open.</dd> <dt><code>aCallback</code></dt> <dd>A function that will be called when the open operation is completed. The callback receives two parameters: the input stream containing the data (implementing {{ interface("nsIInputStream") }}) and the <code>nsresult</code> status code for the open operation.</dd>
</dl>
<h6>Exceptions thrown</h6>
<p>This method throws an exception with the message "Must have a source and a callback" if either <code>aSource</code> or <code>aCallback</code> is null.</p>
<h4>Example</h4>
<p>This example shows the basic code consumers would need to implement to be correct.</p>
<pre class="brush: js">NetUtil.asyncFetch(channel, function(aInputStream, aResult) {
  // Check that we had success.
  if (!Components.isSuccessCode(aResult)) {
    // Handle error
    return;
  }

  // Consume the input stream.
});</pre><h3>newURI</h3>
<p>The <code>newURI()</code> method creates a new {{ interface("nsIURI") }}. This method wraps the {{ ifandmethod("nsIIOService", "newURI") }}.</p>
<pre>nsIURI newURI(
  aSpec,
  [optinoal] aOriginCharset,
  [optional] aBaseURI
); 
</pre>
<h6>Parameters</h6>
<dl> <dt><code>aSpec</code></dt> <dd>The spec for the desired URI.</dd> <dt><code>aOriginCharset</code></dt> <dd>The optional character set for the URI. Defaults to UTF-8 if not provided.</dd> <dt><code>aBaseURI</code></dt> <dd>The base URI for the spec.</dd>
</dl>
<h6>Return value</h6>
<p>Returns the {{ interface("nsIURI") }} object representing <code>aSpec</code>.</p>
<h6>Exceptions thrown</h6>
<p>This method throws an exception with the message "Must have a non-null spec" and result code <code>NS_ERROR_INVALID_ARG</code> if <code>aSpec</code> is null.</p>
<h2>See also</h2>
<ul> <li><a class="internal" href="/en/JavaScript_code_modules/Using_JavaScript_code_modules" title="en/JavaScript code modules/Using JavaScript code modules">Using JavaScript code modules</a></li> <li><a class="internal" href="/en/JavaScript_code_modules" title="en/JavaScript code modules">JavaScript code modules</a></li> <li><a class="internal" href="/en/Components.utils.import" title="en/Components.utils.import"><code>Components.utils.import</code></a></li>
</ul>
Revert to this revision