Read a file with Rust WASM

766 views Asked by At

I am trying to read a file called Book.txt within my Rust yew app. I am serving Book.txt using trunk's copy-file so that it is accessible from http://localhost:8080/Book.txt. Trying to read the file using std::fs did not work (with error Could not open file: Error { kind: Unsupported, message: "operation not supported on this platform" }), but I'm wondering if there is some other way to read this file. I tried to also use the wasm32-unknown-emscripten target but that didn't seem to do anything. I would really like to avoid if at all possible having a client-server architecture for this where I have the file on the server and read it there as I would like to eventually host this all on github pages.

Help is much appreciated.

Thank you!

1

There are 1 answers

3
Caesar On BEST ANSWER
  • std::fs accesses the local filesystem. In case of a web app, the local platform is the browser. There is no file system in the browser, so there is nothing to access, hence it fails with the error message you showed.
    • Emscripten actually emulates a local in-memory filesystem in the browser, and there should be some way of pre-seeding that filesystem with files. But I have no idea how to do that in Rust, and in general, it doesn't hold much benefit over the next option:
  • The easiest way for you to have the content of the file would be to use std::include_str!. But that will include the content in the compiled output, which may not be what you want if Book.txt is huge and not always needed, or if you want to change it after you finish compiling.
  • Since you are already serving Book.txt via http, you should be able to request it through XHR, either using "raw" APIs like web_sys::Window::fetch_with_request_and_init, or through some convenience crate like reqwest. (If that doesn't work, make sure you're not running into CORS limitations.)