Skip to content

Chrome Native Filesystem API #169

Closed

Description

@jaredpalmer

Chrome has a new filesystem API that could be of interest. This would allow save/open from user filesystem. IIRC, if you add a service worker (kinda scary) to make the PWA installable, you can keep user permissions between refreshes in indexdb.

More here: https://web.dev/native-file-system/

I played around with this w/ CRA and Workbbox for a newsletter builder recently. Final FS api is pretty sweet:

/**
 * Open a handle to an existing file on the local file system.
 *
 * @return {!Promise<FileSystemFileHandle>} Handle to the existing file.
 */
export function getFileHandle() {
  const handle = (window as any).chooseFileSystemEntries();
  return handle;
}

/**
 * Create a handle to a new (text) file on the local file system.
 *
 * @return {!Promise<FileSystemFileHandle>} Handle to the new file.
 */
export function getNewFileHandle() {
  const opts = {
    type: 'saveFile',
    accepts: [
      {
        description: 'Text file',
        extensions: ['txt'],
        mimeTypes: ['text/plain'],
      },
    ],
  };
  const handle = (window as any).chooseFileSystemEntries(opts);
  return handle;
}

/**
 * Reads the raw text from a file.
 *
 * @param {File} file
 * @return {!Promise<string>} A promise that resolves to the parsed string.
 */
export function readFile(file: any) {
  // If the new .text() reader is available, use it.
  if (file.text) {
    return file.text();
  }
  // Otherwise use the traditional file reading technique.
  return _readFileLegacy(file);
}

/**
 * Reads the raw text from a file.
 *
 * @private
 * @param {File} file
 * @return {Promise<string>} A promise that resolves to the parsed string.
 */
function _readFileLegacy(file: any) {
  return new Promise(resolve => {
    const reader = new FileReader();
    reader.addEventListener('loadend', e => {
      const text = (e as any).srcElement.result;
      resolve(text);
    });
    reader.readAsText(file);
  });
}

/**
 * Writes the contents to disk.
 *
 * @param {FileSystemFileHandle} fileHandle File handle to write to.
 * @param {string} contents Contents to write.
 */
export async function writeFile(fileHandle: any, contents: any) {
  // Create a writer
  const writer = await fileHandle.createWriter();
  // Make sure we start with an empty file
  await writer.truncate(0);
  // Write the full length of the contents
  await writer.write(0, contents);
  // Close the file and write the contents to disk
  await writer.close();
}

Activity

  1. added a commit that references this issue on Jul 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions