Using the filesystem
Each computer includes a full filesystem that persists across sessions. You can create, read, write, and delete files and directories just like on a local machine. In this guide, we'll walk through the filesystem operations.
Read and write files
You can read and write files to the computer's filesystem using the fs.writeFile
and fs.readFile
methods.
import { Computer } from "@metallichq/sdk";
// Start computer
const computer = await Computer.start("your-computer-id");
await computer.waitForState("started");
// Write file
await computer.fs.writeFile("hello.txt", "Hello, world!");
// Read file
const fileContent = await computer.fs.readFile("hello.txt");
console.log(fileContent); // "Hello, world!"
// Stop computer
await computer.stop();
Create directory
You can create directories using the fs.createDirectory
method.
import { Computer } from "@metallichq/sdk";
// Start computer
const computer = await Computer.start("your-computer-id");
await computer.waitForState("started");
// Create directory
await computer.fs.createDirectory("new-project");
// Read directory
const files = await computer.fs.listDirectory("new-project");
console.log(files);
// Stop computer
await computer.stop();
Watch directory for changes
You can watch a directory for changes using the fs.watch
method.
import { Computer } from "@metallichq/sdk";
// Start computer
const computer = await Computer.start("your-computer-id");
await computer.waitForState("started");
// Watch directory
const handle = await computer.fs.watch("new-project", async (event) => {
console.log(event)
if (event.type === "CREATED") {
console.log(`File created: ${event.path}`)
}
});
// Stop watching
await handle.stop();
// Stop computer
await computer.stop();
Additional methods
You can also check if a file or directory exists (fs.exists
), get the stats of a file or directory (fs.getStats
), and delete a file or directory (fs.delete
).
import { Computer } from "@metallichq/sdk";
// Start computer
const computer = await Computer.start("your-computer-id");
await computer.waitForState("started");
// Check if file or directory exists
const exists = await computer.fs.exists("hello.txt");
console.log(exists); // true or false
// Get file or directory stats
const stats = await computer.fs.getStats("hello.txt");
console.log(stats);
// Delete file or directory
await computer.fs.delete("hello.txt");
// Stop computer
await computer.stop();