fs.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var dirSelect = document.getElementById("dir");
  2. function getDir() {
  3. return dirSelect.value ? parseInt(dir.value) : null;
  4. }
  5. function arrayBufferToBase64(buffer, callback) {
  6. var blob = new Blob([buffer], {
  7. type: "application/octet-binary",
  8. });
  9. var reader = new FileReader();
  10. reader.onload = function (evt) {
  11. var dataurl = evt.target.result;
  12. callback(dataurl.substr(dataurl.indexOf(",") + 1));
  13. };
  14. reader.readAsDataURL(blob);
  15. }
  16. var pathInput = document.getElementById("path-to-read");
  17. addClickEnterHandler(document.getElementById("read"), pathInput, function () {
  18. var pathToRead = pathInput.value;
  19. var isFile = pathToRead.match(/\S+\.\S+$/g);
  20. var opts = {
  21. dir: getDir(),
  22. };
  23. var promise = isFile
  24. ? window.__TAURI__.fs.readBinaryFile(pathToRead, opts)
  25. : window.__TAURI__.fs.readDir(pathToRead, opts);
  26. promise
  27. .then(function (response) {
  28. if (isFile) {
  29. if (pathToRead.includes(".png") || pathToRead.includes(".jpg")) {
  30. arrayBufferToBase64(new Uint8Array(response), function (base64) {
  31. var src = "data:image/png;base64," + base64;
  32. registerResponse('<img src="' + src + '"></img>');
  33. });
  34. } else {
  35. var value = String.fromCharCode.apply(null, response);
  36. registerResponse(
  37. '<textarea id="file-response" style="height: 400px"></textarea><button id="file-save">Save</button>'
  38. );
  39. var fileInput = document.getElementById("file-response");
  40. fileInput.value = value;
  41. document
  42. .getElementById("file-save")
  43. .addEventListener("click", function () {
  44. window.__TAURI__.fs
  45. .writeFile(
  46. {
  47. file: pathToRead,
  48. contents: fileInput.value,
  49. },
  50. {
  51. dir: getDir(),
  52. }
  53. )
  54. .catch(registerResponse);
  55. });
  56. }
  57. } else {
  58. registerResponse(response);
  59. }
  60. })
  61. .catch(registerResponse);
  62. });