addon-sdk/source/lib/sdk/test/tmp-file.js

branch
TOR_BUG_3246
changeset 7
129ffea94266
equal deleted inserted replaced
-1:000000000000 0:8e2e3e5104c9
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 "use strict";
5
6 const { Cc, Ci } = require("chrome");
7
8 const system = require("sdk/system");
9 const file = require("sdk/io/file");
10 const unload = require("sdk/system/unload");
11
12 // Retrieve the path to the OS temporary directory:
13 const tmpDir = require("sdk/system").pathFor("TmpD");
14
15 // List of all tmp file created
16 let files = [];
17
18 // Remove all tmp files on addon disabling
19 unload.when(function () {
20 files.forEach(function (path){
21 // Catch exception in order to avoid leaking following files
22 try {
23 if (file.exists(path))
24 file.remove(path);
25 }
26 catch(e) {
27 console.exception(e);
28 }
29 });
30 });
31
32 // Utility function that synchronously reads local resource from the given
33 // `uri` and returns content string. Read in binary mode.
34 function readBinaryURI(uri) {
35 let ioservice = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
36 let channel = ioservice.newChannel(uri, "UTF-8", null);
37 let stream = Cc["@mozilla.org/binaryinputstream;1"].
38 createInstance(Ci.nsIBinaryInputStream);
39 stream.setInputStream(channel.open());
40
41 let data = "";
42 while (true) {
43 let available = stream.available();
44 if (available <= 0)
45 break;
46 data += stream.readBytes(available);
47 }
48 stream.close();
49
50 return data;
51 }
52
53 // Create a temporary file from a given string and returns its path
54 exports.createFromString = function createFromString(data, tmpName) {
55 let filename = (tmpName ? tmpName : "tmp-file") + "-" + (new Date().getTime());
56 let path = file.join(tmpDir, filename);
57
58 let tmpFile = file.open(path, "wb");
59 tmpFile.write(data);
60 tmpFile.close();
61
62 // Register tmp file path
63 files.push(path);
64
65 return path;
66 }
67
68 // Create a temporary file from a given URL and returns its path
69 exports.createFromURL = function createFromURL(url, tmpName) {
70 let data = readBinaryURI(url);
71 return exports.createFromString(data, tmpName);
72 }
73

mercurial