javascriptgoogle-chromehtml5-filesystem

Can we use JavaScript FileSystemAPI from a Webworker?


Can we use the JavaScript FileSystemAPI from a webworker?

https://developer.mozilla.org/en-US/docs/Web/API/FileSystem

In their documentation they have not mentioned anything but while using it its throwing window not defined.

Thanks!


Solution

  • Not really...

    There used to be a self.webkitRequestFileSystemSync() method accessible in Worker scopes, but it's been deprecated. And the FileSystem object you'd get from a drop event can't be serialized, and thus can't be posted to Worker from the main thread.

    However, I suspect you don't really want to work with the FileSystem API, which is not really useful in web contexts, but instead you may want to prefer the File System Access API, which gives your page access to the user's file system (even though it's still only available in Chromium based browsers).

    But to use this API from a Web Worker is not simple either.
    To make the request to the File System Access API, we need to be handling an user-gesture. Web Workers don't have access to the UI and thus they don't either have access to UI events (yet).

    So we must make the request from the UI thread.

    However, contrary to FileSystem objects, FileSystemHandles are serializable and can be posted though postMessage(), so once you get the handle, you can post it to your worker and do your work from there.

    In UI thread

    btn.onclick = async (evt) => {
      const dirHandle = await showDirectoryPicker();
      worker.postMessage( dirHandle );
    };
    

    Then in the Worker thread you can receive that handle in the MesageEvent.data, and work with it as you'd do from the main thread.

    Here is a live demo, and its source.