Browser FS Access API Ponyfill

0.38.0 · active · verified Tue Apr 21

browser-fs-access is a JavaScript library that provides a simplified, progressive enhancement approach to using the File System Access API in web browsers. It acts as a ponyfill, meaning it offers a consistent API surface while transparently falling back to older, less capable methods like `<input type="file">` and `<a download>` on browsers that do not fully support the File System Access API. This ensures broad compatibility while leveraging modern capabilities where available. The library is currently at version 0.38.0 and maintains an active release cadence, frequently publishing updates and fixes, often on a monthly basis. Key differentiators include its robust fallback mechanism, its origin from GoogleChromeLabs, and its focus on developer ergonomics by abstracting away the complexities of feature detection and legacy API interactions. It ships with TypeScript types for improved developer experience.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates opening single and multiple files, recursively opening a directory, and saving a file, along with feature detection and error handling using the `browser-fs-access` library.

import { fileOpen, directoryOpen, fileSave, supported } from 'browser-fs-access';

async function performFileOperations() {
  if (supported) {
    console.log('Using the File System Access API.');
  } else {
    console.log('Using the fallback implementation (e.g., <input type="file"> or <a download>).');
  }

  try {
    // Open a single image file with specific options
    const imageBlob = await fileOpen({
      mimeTypes: ['image/*'],
      extensions: ['.png', '.jpg', '.jpeg'],
      description: 'Select an image file',
      multiple: false,
      startIn: 'pictures'
    });
    console.log(`Opened image: ${imageBlob.name} (type: ${imageBlob.type}, size: ${imageBlob.size} bytes)`);

    // Open multiple text files from a directory, recursively
    const filesInDir = await directoryOpen({
      recursive: true,
      mode: 'read',
      mimeTypes: ['text/*', 'application/json'],
      extensions: ['.txt', '.md', '.json']
    });
    console.log(`Opened ${filesInDir.length} files in directory. First file: ${filesInDir[0]?.name || 'N/A'}`);

    // Save a new text file created from a Blob
    const textContent = 'This is a test file saved using browser-fs-access.\nHello, world!';
    const textBlob = new Blob([textContent], { type: 'text/plain' });
    await fileSave(textBlob, {
      fileName: 'my-document.txt',
      extensions: ['.txt'],
      description: 'My Text Document',
      startIn: 'documents'
    });
    console.log('Successfully saved my-document.txt');

  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('User cancelled the file picker.');
    } else {
      console.error('File operation failed:', error);
    }
  }
}

performFileOperations();

view raw JSON →