opfs.cljs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. (ns frontend.common.file.opfs
  2. "OPFS fs api"
  3. (:require [promesa.core :as p]))
  4. (defn <write-text!
  5. "Write `text` to `filename` in Origin Private File System.
  6. Returns a promise."
  7. [filename text]
  8. (p/let [;; OPFS root dir
  9. root (.. js/navigator -storage (getDirectory))
  10. ;; get (or create) a file handle
  11. file-handle (.getFileHandle root filename #js {:create true})
  12. ;; open a writable stream
  13. writable (.createWritable file-handle)]
  14. ;; write string directly
  15. (.write writable text)
  16. ;; always close!
  17. (.close writable)))
  18. (defn <read-text!
  19. "Read text content from `filename` in Origin Private File System (OPFS).
  20. Returns a promise that resolves to the file content string."
  21. [filename]
  22. (p/let [root (.. js/navigator -storage (getDirectory))
  23. file-handle (.getFileHandle root filename)
  24. file (.getFile file-handle)]
  25. (.text file)))
  26. (comment
  27. (defn <delete-file!
  28. "Delete `filename` from Origin Private File System.
  29. Options:
  30. - :ignore-not-found? (default true) → don't treat missing file as error.
  31. Returns a promise that resolves to nil."
  32. [filename & {:keys [ignore-not-found?]
  33. :or {ignore-not-found? true}}]
  34. (-> (p/let [root (.. js/navigator -storage (getDirectory))]
  35. (.removeEntry root filename))
  36. (p/catch (fn [err]
  37. (if (and ignore-not-found?
  38. (= (.-name err) "NotFoundError"))
  39. nil
  40. (throw err)))))))