|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 "use strict"; |
|
6 |
|
7 module.metadata = { |
|
8 "stability": "experimental" |
|
9 }; |
|
10 |
|
11 const { Cu, components } = require("chrome"); |
|
12 const { defer } = require("../core/promise"); |
|
13 const { merge } = require("../util/object"); |
|
14 |
|
15 const { NetUtil } = Cu.import("resource://gre/modules/NetUtil.jsm", {}); |
|
16 |
|
17 /** |
|
18 * Reads a URI and returns a promise. |
|
19 * |
|
20 * @param uri {string} The URI to read |
|
21 * @param [options] {object} This parameter can have any or all of the following |
|
22 * fields: `charset`. By default the `charset` is set to 'UTF-8'. |
|
23 * |
|
24 * @returns {promise} The promise that will be resolved with the content of the |
|
25 * URL given. |
|
26 * |
|
27 * @example |
|
28 * let promise = readURI('resource://gre/modules/NetUtil.jsm', { |
|
29 * charset: 'US-ASCII' |
|
30 * }); |
|
31 */ |
|
32 function readURI(uri, options) { |
|
33 options = options || {}; |
|
34 let charset = options.charset || 'UTF-8'; |
|
35 |
|
36 let channel = NetUtil.newChannel(uri, charset, null); |
|
37 |
|
38 let { promise, resolve, reject } = defer(); |
|
39 |
|
40 try { |
|
41 NetUtil.asyncFetch(channel, function (stream, result) { |
|
42 if (components.isSuccessCode(result)) { |
|
43 let count = stream.available(); |
|
44 let data = NetUtil.readInputStreamToString(stream, count, { charset : charset }); |
|
45 |
|
46 resolve(data); |
|
47 } else { |
|
48 reject("Failed to read: '" + uri + "' (Error Code: " + result + ")"); |
|
49 } |
|
50 }); |
|
51 } |
|
52 catch (e) { |
|
53 reject("Failed to read: '" + uri + "' (Error: " + e.message + ")"); |
|
54 } |
|
55 |
|
56 return promise; |
|
57 } |
|
58 |
|
59 exports.readURI = readURI; |
|
60 |
|
61 /** |
|
62 * Reads a URI synchronously. |
|
63 * This function is intentionally undocumented to favorites the `readURI` usage. |
|
64 * |
|
65 * @param uri {string} The URI to read |
|
66 * @param [charset] {string} The character set to use when read the content of |
|
67 * the `uri` given. By default is set to 'UTF-8'. |
|
68 * |
|
69 * @returns {string} The content of the URI given. |
|
70 * |
|
71 * @example |
|
72 * let data = readURISync('resource://gre/modules/NetUtil.jsm'); |
|
73 */ |
|
74 function readURISync(uri, charset) { |
|
75 charset = typeof charset === "string" ? charset : "UTF-8"; |
|
76 |
|
77 let channel = NetUtil.newChannel(uri, charset, null); |
|
78 let stream = channel.open(); |
|
79 |
|
80 let count = stream.available(); |
|
81 let data = NetUtil.readInputStreamToString(stream, count, { charset : charset }); |
|
82 |
|
83 stream.close(); |
|
84 |
|
85 return data; |
|
86 } |
|
87 |
|
88 exports.readURISync = readURISync; |