tmp-file.js 2.1 KB

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