Tobias Langner
Tobias Langner

Reputation: 10808

Can I read files from the disk by using Webassembly? (re-evaluated)

what's currently possible in webassembly running in the browser regarding accessing the local file system? There's an older question that says it's not possible due to security restrictions. But some places (e.g. https://fjolt.com/article/javascript-new-file-system-api) say that there's a new file system API available in some browsers that would allow that.

a) what needs to be done to be able to use that api? b) can I use it from rust with webassembly - and how?

Thank you for any useful pointer. Tobias

Upvotes: 5

Views: 4030

Answers (2)

Robert Cutajar
Robert Cutajar

Reputation: 3701

It is important to distinguish wasm in the browser and in the wild. WASM in the browser is naturally very restricted. But there is a way to run WASM directly (WASI), like you would run javascript in node.js, which should have APIs for accessing the file system without restrictions. Here I focus on WASM in the browser.

The new FileSystem APIs allow you to use a sandboxed filesystem. It is only accessible to the originating website (other websites cannot access). And you cannot get to the host files, it is a virtual space managed by the browser.

For example with Rust wasm, use the navigator.storage.get_directory to get the top level directory handle. From there you can work with the filesystem APIs.

Upvotes: 3

user18074821
user18074821

Reputation: 216

The current web APIs (https://developer.mozilla.org/en-US/docs/Web/API) only lets you access files in the local files system by prompting the user to open or save files. These APIs are not (yet) accesible from webassembly directly. So what you have to do is

  1. Use javascript to prompt the user to open a file (or directory)
  2. Grab the contents of the file and pass it to your webassembly code
  3. Process the contents with webassembly (or in your case rust compiled to webassembly)
  4. Pass the processed content back to javascript that can prompt the user to save the file.

or some variation of the theme above. Read more about webassmbly usage here https://developer.mozilla.org/en-US/docs/WebAssembly/Using_the_JavaScript_API

and Rust and webassembly e.g. here

https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_wasm

Upvotes: 4

Related Questions