Description
For getting a FileSystemSyncAccessHandle
, you need a FileSystemFileHandle
first, which, in a Worker, where you want to work with the all-sync file methods, you generally don't have much use for, so you could "skip" it as below:
// In a `Worker`.
const root = await navigator.storage.getDirectory();
const accessHandle = await (await root.getFileHandle('fast', {create: true})).createSyncAccessHandle();
If, however, you decide at some point wanting to transfer the file from the OPFS over to the user-visible file system, you now need to postMessage()
a FileSystemFileHandle
in order to let the user run showSaveFilePicker()
over on the main thread, where you can then write()
the File
you obtain via getFile()
.
Would it make sense to add a FileSystemSyncAccessHandle.fileHandle
property, that would point at the associated FileSystemFileHandle
? This would enable the following flow:
// In the `Worker`.
const root = await navigator.storage.getDirectory();
const accessHandle = await (await root.getFileHandle('fast', {create: true})).createSyncAccessHandle();
/* … */
self.postMessage('save', [accessHandle.fileHandle]);
// On the main thread after receiving the message with the `FileSystemFileHandle`.
/* … */
const saveHandle = await showSaveFilePicker();
const writable = await saveHandle.createWritable();
await writable.write(await fileHandle.getFile());
await writable.close();
(The alternative would be to just keep a reference around to the FileSystemFileHandle
in the Worker until it's needed. It's really mostly a potential ergonomics improvement. Thoughts?)