ShowOpenFilePicker Feature Guard

Open the OS file dialog from a click handler with showOpenFilePicker, feature-guard the API surface, and treat AbortError as a dismissed dialog.

TypescriptFile Upload

Code

typescriptsnippet
44 lines
// showOpenFilePicker feature guard: it must run inside a user gesture, and
// TS 5.6's lib.dom predates the API, so its surface is declared here
interface OpenFilePickerOptions {
  readonly types?: readonly {
    readonly description?: string;
    readonly accept: Record<string, readonly string[]>;
  }[];
  readonly multiple?: boolean;
}
type ShowOpenFilePicker = (options?: OpenFilePickerOptions) => Promise<FileSystemFileHandle[]>;

async function pickLogFile(open: () => Promise<FileSystemFileHandle[]>): Promise<string> {
  const [handle] = await open();
  const file = await handle.getFile();
  return `${file.name} (${file.size} bytes)`;
}

if (typeof window === "undefined") {
  console.log("showOpenFilePicker needs a browser DOM");
} else {
  const { showOpenFilePicker } = window as unknown as { showOpenFilePicker?: ShowOpenFilePicker };
  const button = document.querySelector<HTMLButtonElement>("#pick-log");
  button?.addEventListener("click", () => {
    if (!showOpenFilePicker) {
      console.log("browser lacks the File System Access API");
      return;
    }
    pickLogFile(() =>
      showOpenFilePicker({
        types: [{ description: "Log files", accept: { "text/plain": [".log", ".txt"] } }],
        multiple: false,
      })
    )
      .then((summary) => console.log("picked:", summary))
      .catch((error: unknown) => {
        // AbortError means the user dismissed the dialog, not a failure
        if (error instanceof DOMException && error.name === "AbortError") {
          console.log("picker dismissed");
        } else {
          throw error;
        }
      });
  });
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

showOpenFilePicker needs a browser DOM

How the logic is organized

ShowOpenFilePicker Feature Guard reduces to the function pickLogFile.

await marks each async boundary — nothing fires and forgets.

Caveats

  • Imports, if present, point only at standard-library modules.
  • document, window exist only in browsers — a Node runtime has no shims for them out of the box.

Using it

The principal routine signature: async function pickLogFile(open: ()

Lines print with tags — showOpenFilePicker needs a browser DOM, browser lacks the File System Access API, picked: — when the file runs.

Key statements

type ShowOpenFilePicker = (options?: OpenFilePickerOptions) => Promise<FileSystemFileHandle[]>;
async function pickLogFile(open: () => Promise<FileSystemFileHandle[]>): Promise<string> {
  const [handle] = await open();
  const file = await handle.getFile();
  return `${file.name} (${file.size} bytes)`;
}
.catch((error: unknown) => {
  // AbortError means the user dismissed the dialog, not a failure
  if (error instanceof DOMException && error.name === "AbortError") {
    console.log("picker dismissed");
  } else {
    throw error;
  }
});

Interactive Tools for This Topic

FAQ

Does ShowOpenFilePicker Feature Guard run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.