From 410c875e048b67af62c0a75d6c0d6326c485af8a Mon Sep 17 00:00:00 2001 From: Gyeongjae Choi Date: Wed, 4 May 2022 19:43:34 +0900 Subject: [PATCH] DOC Add documentation entry about file system access (#2420) Co-authored-by: Roman Yurchak Co-authored-by: Hood Chatham Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/usage/file-system.md | 49 +++++++++++++++++++++++++++++++++++++++ docs/usage/index.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 docs/usage/file-system.md diff --git a/docs/usage/file-system.md b/docs/usage/file-system.md new file mode 100644 index 000000000..d041d11ec --- /dev/null +++ b/docs/usage/file-system.md @@ -0,0 +1,49 @@ +(file-system)= + +# Dealing with the file system + +Pyodide includes a file system provided by Emscripten. +In JavaScript, the Pyodide file system can be accessed through {any}`pyodide.FS` which re-exports the [Emscripten File System API](https://emscripten.org/docs/api_reference/Filesystem-API.html#filesystem-api) + +**Example: Reading from the file system** + +```js +pyodide.runPython(` + with open("/hello.txt", "w") as fh: + fh.write("hello world!") +`); + +let file = pyodide.FS.readFile("/hello.txt", { encoding: "utf8" }); +console.log(file); // ==> "hello world!" +``` + +**Example: Writing to the file system** + +```js +let data = "hello world!"; +pyodide.FS.writeFile("/hello.txt", data, { encoding: "utf8" }); +pyodide.runPython(` + with open("/hello.txt", "r") as fh: + data = fh.read() + print(data) +`); +``` + +## Mounting a file system + +The default file system used in Pyodide is [MEMFS](https://emscripten.org/docs/api_reference/Filesystem-API.html#memfs), +which is a virtual in-memory file system. The data stored in MEMFS will be lost when the page is reloaded. + +If you wish for files to persist, you can mount other file systems. +Other file systems provided by Emscripten are `IDBFS`, `NODEFS`, `PROXYFS`, `WORKERFS`. +Note that some filesystems can only be used in specific runtime environments. +See [Emscripten File System API](https://emscripten.org/docs/api_reference/Filesystem-API.html#filesystem-api) for more details. +For instance, to store data persistently between page reloads, one could mount +a folder with the +[IDBFS file system](https://emscripten.org/docs/api_reference/Filesystem-API.html#filesystem-api-idbfs) + +```js +let mountDir = "/mnt"; +pyodide.FS.mkdir(mountDir); +pyodide.FS.mount(pyodide.FS.filesystems.IDBFS, { root: "." }, mountDir); +``` diff --git a/docs/usage/index.md b/docs/usage/index.md index 18358c519..27d61511a 100644 --- a/docs/usage/index.md +++ b/docs/usage/index.md @@ -120,4 +120,5 @@ For this same reason, installing Pyodide packages from the CDN is explicitly not webworker.md loading-custom-python-code.md + file-system.md ```