GoogleChromeLabs / browser-fs-access

File System Access API with legacy fallback in the browser
https://googlechromelabs.github.io/browser-fs-access/demo/
Apache License 2.0
1.38k stars 84 forks source link

Is it possible to read a file more than once? #86

Closed gbishop closed 2 years ago

gbishop commented 2 years ago

My user is creating a file for input. They load it, see a problem, fix the problem in an external editor, and then want to load it again.

It would be great if I could save them the bother of browsing to it again. I'd like to give them a Reload button.

I can write a file more than once by saving the fileHandle, can I read more than once?

tomayac commented 2 years ago

You can do this. See the demo and check out its source code (also embedded below).

import { fileOpen, supported } from "https://unpkg.com/browser-fs-access@0.23.0/dist/esm/index.js";

const open = document.querySelector("button");
const reload = document.querySelector("button[disabled]");
const text = document.querySelector("textarea");

let handle = null;

open.addEventListener("click", async () => {
  try {
    const blob = await fileOpen();
    if (supported && blob) {
      reload.disabled = false;
      handle = blob.handle;
      text.textContent = await blob.text();
    }
  } catch {
    handle = null;
    reload.disabled = true;
  }
});

reload.addEventListener("click", async () => {
  if (supported && handle) {
    const file = await handle.getFile();
    text.textContent = await file.text();
  }
});
gbishop commented 2 years ago

Great! Thanks for the explanation. I had missed this.