FileUtils.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * File utils is used to read and write files.
  3. *
  4. * Can be used alongside with object serialization to store and load objects from file.
  5. *
  6. * @class
  7. * @static
  8. */
  9. function FileUtils(){}
  10. /**
  11. * Read a local or remote file as text data.
  12. *
  13. * @param {string} fname Path or URL of the file being read.
  14. * @param {Function} onLoad onLoad callback receives the read data as parameter.
  15. * @param {Function} onError onError call is called when a error occurs while reading the file.
  16. */
  17. FileUtils.read = function(fname, onLoad, onError)
  18. {
  19. var file = new XMLHttpRequest();
  20. file.overrideMimeType("text/plain");
  21. file.open("GET", fname, true);
  22. if(onLoad !== undefined)
  23. {
  24. file.onload = function()
  25. {
  26. onLoad(file.response);
  27. };
  28. }
  29. if(onError !== undefined)
  30. {
  31. file.onerror = onError;
  32. }
  33. file.send(null);
  34. };
  35. /**
  36. * Write text to a file and automatically download it from blob storage.
  37. *
  38. * @method writeFile
  39. * @param {string} fname Path of the file to write.
  40. * @param {string} data Text data to be written to the file.
  41. */
  42. FileUtils.write = function(fname, data)
  43. {
  44. var blob = new Blob([data], {type:"octet/stream"});
  45. var download = document.createElement("a");
  46. download.download = fname;
  47. download.href = window.URL.createObjectURL(blob);
  48. download.style.display = "none";
  49. download.onclick = function()
  50. {
  51. document.body.removeChild(this);
  52. };
  53. document.body.appendChild(download);
  54. download.click();
  55. };
  56. export {FileUtils};