File System
Every sandbox has a persistent file system in the default working directory: /project/workspace
. All files saved in /project/workspace
have git
source control and will be persisted between reboots. Whenever we hibernate or shutdown a sandbox, we create a commit to track the filesystem of the sandbox.
Refer to the Environment section for more information about how we store files and other resources.
API
The API of the filesystem is similar to the Node.js fs module. You can find the API under sandbox.fs
. All filesystem
operations are relative to the workspace directory of the sandbox (which is /project/workspace
by default).
Writing & Reading Files
You can read & write files using an api that's similar to the Node.js fs module:
// Writing text files
await client.fs.writeTextFile("./hello.txt", "Hello, world!");
// Reading text files
const content = await client.fs.readTextFile("./hello.txt");
console.log(content);
// Writing binary files
await client.fs.writeFile("./hello.bin", new Uint8Array([1, 2, 3]));
// Reading binary files
const content = await client.fs.readFile("./hello.bin");
console.log(content);
Uploading & Downloading Files
Uploading and downloading files can be done using the same methods.
import fs from "node:fs";
const myBinaryFile = fs.readFileSync("./my-binary-file");
await client.fs.writeFile("./my-binary-file", myBinaryFile);
const content = await client.fs.readFile("./my-binary-file");
fs.writeFileSync("./my-binary-file", content);
You can also download a file or directory as a zip file by generating a download URL. This URL is valid for 5 minutes:
const { downloadUrl } = await client.fs.download("./");
console.log(downloadUrl);
Listing Files & Directories
You can list files & directories in a directory using the readdir
method.
const filesOrDirs = await client.fs.readdir("./");
console.log(filesOrDirs);
Copying, Renaming & Deleting Files
You can copy, rename & delete files using the copy
, rename
& remove
methods.
await client.fs.copy("./hello.txt", "./hello-copy.txt");
await client.fs.rename("./hello-copy.txt", "./hello-renamed.txt");
await client.fs.remove("./hello-renamed.txt");
Watching Files
You can watch files for file changes, additions and deletions using the watch
method.
const watcher = await client.fs.watch("./", { recursive: true, excludes: [".git"] });
watcher.onEvent((event) => {
console.log(event);
});
// When you're done, you can stop the watcher
watcher.dispose();
Storage (Mounts)
You can learn more about the different folders to store files in the Sessions documentation.