jvilk / BrowserFS

BrowserFS is an in-browser filesystem that emulates the Node JS filesystem API and supports storing and retrieving files from various backends.
Other
3.06k stars 216 forks source link

Can BrowserFS be used to interact with OPFS #377

Closed philipp-strack closed 3 months ago

philipp-strack commented 3 months ago

Hi,

can BrowserFS interact with the origin protected filesystem (https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system).

I found this PR

https://github.com/jvilk/BrowserFS/pull/321

but could not understand how to make this work. Thank you!

james-pre commented 3 months ago

@philipp-strack,

You can use the Origin Private File System (OPFS) using the FileSystemAccess backend:

import { configure, fs } from '@browserfs/core';
import { FileSystemAccess } from '@browserfs/dom';

await configure({ backend: FileSystemAccess, handle: await navigator.storage.getDirectory() });

// usage example
if(!(await fs.promises.exists('/myfile'))) {
    await fs.promises.writeFile('myfile', 'this will persist in the OPFS'); // PWD is /
}

const contents = await fs.promises.readFile('/myfile', 'utf-8');

console.log(contents);

[!IMPORTANT] FileSystemAccess is an asynchronous backend. You can not use synchronous functions (e.g. readFileSync) unless you first wrap it in an AsyncMirror.

philipp-strack commented 3 months ago

Thank you that is super helpful!!

james-pre commented 3 months ago

@philipp-strack,

Of course!

I made a mistake in my original code but I fixed it in an edit, so please use the edited code (I assigned the handle to backend, which was not correct)