or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

filesystem.mdindex.mdwasi-runtime.md

filesystem.mddocs/

0

# Filesystem

1

2

In-memory filesystem operations enabling WASI programs to work with files and directories without requiring host filesystem access. The MemFS (Memory Filesystem) provides a complete sandboxed filesystem that exists only in memory, perfect for secure WebAssembly execution across all JavaScript environments.

3

4

## Capabilities

5

6

### MemFS Class

7

8

In-memory filesystem providing POSIX-like file operations.

9

10

```typescript { .api }

11

/**

12

* In-memory filesystem for WASI sandboxed file operations

13

*/

14

class MemFS {

15

/**

16

* Create a new empty in-memory filesystem

17

*/

18

constructor();

19

20

/**

21

* Create MemFS instance from JavaScript object structure

22

* @param jso - JavaScript object representing filesystem structure

23

* @returns New MemFS instance

24

*/

25

static from_js(jso: any): MemFS;

26

27

/**

28

* Read directory contents

29

* @param path - Directory path to read

30

* @returns Array of directory entries with path and metadata

31

*/

32

readDir(path: string): Array<any>;

33

34

/**

35

* Create a directory

36

* @param path - Directory path to create

37

*/

38

createDir(path: string): void;

39

40

/**

41

* Remove a directory (must be empty)

42

* @param path - Directory path to remove

43

*/

44

removeDir(path: string): void;

45

46

/**

47

* Remove a file

48

* @param path - File path to remove

49

*/

50

removeFile(path: string): void;

51

52

/**

53

* Rename or move a file or directory

54

* @param path - Current path

55

* @param to - New path

56

*/

57

rename(path: string, to: string): void;

58

59

/**

60

* Get file or directory metadata

61

* @param path - Path to get metadata for

62

* @returns Object containing file metadata (size, timestamps, type)

63

*/

64

metadata(path: string): object;

65

66

/**

67

* Open a file for reading/writing

68

* @param path - File path to open

69

* @param options - File open options (read, write, create, etc.)

70

* @returns JSVirtualFile handle for file operations

71

*/

72

open(path: string, options: any): JSVirtualFile;

73

74

/**

75

* Free WebAssembly resources

76

* Call when done with the filesystem to clean up memory

77

*/

78

free(): void;

79

}

80

```

81

82

**Usage Examples:**

83

84

```typescript

85

import { MemFS } from "@wasmer/wasi";

86

87

// Create filesystem and directory structure

88

const fs = new MemFS();

89

fs.createDir("/app");

90

fs.createDir("/data");

91

fs.createDir("/tmp");

92

93

// List directory contents

94

const rootContents = fs.readDir("/");

95

console.log("Root directory:", rootContents.map(entry => entry.path));

96

97

// Work with files

98

const file = fs.open("/data/config.json", {

99

read: true,

100

write: true,

101

create: true

102

});

103

104

file.writeString('{"setting": "value"}');

105

file.seek(0);

106

const content = file.readString();

107

console.log("File content:", content);

108

109

// File operations

110

fs.rename("/data/config.json", "/data/settings.json");

111

const metadata = fs.metadata("/data/settings.json");

112

console.log("File size:", metadata.size);

113

114

// Cleanup

115

fs.removeFile("/data/settings.json");

116

fs.removeDir("/data");

117

```

118

119

### JSVirtualFile Class

120

121

Virtual file handle providing comprehensive file I/O operations.

122

123

```typescript { .api }

124

/**

125

* Virtual file handle for in-memory filesystem operations

126

*/

127

class JSVirtualFile {

128

/**

129

* Get last access time

130

* @returns Last access timestamp as BigInt

131

*/

132

lastAccessed(): bigint;

133

134

/**

135

* Get last modification time

136

* @returns Last modification timestamp as BigInt

137

*/

138

lastModified(): bigint;

139

140

/**

141

* Get file creation time

142

* @returns Creation timestamp as BigInt

143

*/

144

createdTime(): bigint;

145

146

/**

147

* Get current file size

148

* @returns File size in bytes as BigInt

149

*/

150

size(): bigint;

151

152

/**

153

* Set file size (truncate or extend)

154

* @param new_size - New file size in bytes

155

*/

156

setLength(new_size: bigint): void;

157

158

/**

159

* Read entire file contents as bytes

160

* @returns File contents as Uint8Array

161

*/

162

read(): Uint8Array;

163

164

/**

165

* Read entire file contents as string

166

* @returns File contents as UTF-8 string

167

*/

168

readString(): string;

169

170

/**

171

* Write bytes to file at current position

172

* @param buf - Data to write as Uint8Array

173

* @returns Number of bytes written

174

*/

175

write(buf: Uint8Array): number;

176

177

/**

178

* Write string to file at current position

179

* @param buf - Data to write as UTF-8 string

180

* @returns Number of bytes written

181

*/

182

writeString(buf: string): number;

183

184

/**

185

* Flush any pending writes to the filesystem

186

*/

187

flush(): void;

188

189

/**

190

* Seek to a specific position in the file

191

* @param position - Byte position to seek to

192

* @returns New current position

193

*/

194

seek(position: number): number;

195

196

/**

197

* Free WebAssembly resources

198

* Call when done with the file handle to clean up memory

199

*/

200

free(): void;

201

}

202

```

203

204

**File Operation Examples:**

205

206

```typescript

207

import { MemFS } from "@wasmer/wasi";

208

209

const fs = new MemFS();

210

211

// Create and write to a text file

212

const textFile = fs.open("/example.txt", {

213

read: true,

214

write: true,

215

create: true

216

});

217

218

textFile.writeString("Hello, WASI filesystem!\n");

219

textFile.writeString("This is line 2.\n");

220

textFile.flush();

221

222

console.log("File size:", textFile.size());

223

console.log("Created:", new Date(Number(textFile.createdTime())));

224

225

// Read from beginning

226

textFile.seek(0);

227

const content = textFile.readString();

228

console.log("File content:", content);

229

230

// Binary file operations

231

const binaryFile = fs.open("/data.bin", {

232

read: true,

233

write: true,

234

create: true

235

});

236

237

// Write binary data

238

const data = new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F]); // "Hello"

239

const bytesWritten = binaryFile.write(data);

240

console.log("Wrote", bytesWritten, "bytes");

241

242

// Read binary data

243

binaryFile.seek(0);

244

const readData = binaryFile.read();

245

console.log("Read bytes:", Array.from(readData).map(b => b.toString(16)));

246

247

// File manipulation

248

textFile.seek(0);

249

textFile.setLength(5n); // Truncate to 5 bytes

250

textFile.seek(0);

251

const truncated = textFile.readString();

252

console.log("Truncated:", truncated); // "Hello"

253

```

254

255

### File Open Options

256

257

File opening options for controlling access mode and behavior.

258

259

```typescript { .api }

260

// File open options (passed to MemFS.open)

261

interface FileOpenOptions {

262

read?: boolean; // Allow reading from file

263

write?: boolean; // Allow writing to file

264

create?: boolean; // Create file if it doesn't exist

265

truncate?: boolean; // Truncate file to zero length on open

266

append?: boolean; // Start writing at end of file

267

}

268

```

269

270

**File Mode Examples:**

271

272

```typescript

273

// Read-only access

274

const readFile = fs.open("/readonly.txt", { read: true });

275

276

// Write-only with creation

277

const writeFile = fs.open("/output.log", {

278

write: true,

279

create: true

280

});

281

282

// Read-write with truncation

283

const rwFile = fs.open("/temp.dat", {

284

read: true,

285

write: true,

286

create: true,

287

truncate: true

288

});

289

290

// Append mode

291

const logFile = fs.open("/app.log", {

292

write: true,

293

create: true,

294

append: true

295

});

296

```

297

298

### Filesystem Integration with WASI

299

300

The MemFS integrates seamlessly with WASI instances for program file access.

301

302

**Integration Examples:**

303

304

```typescript

305

import { init, WASI, MemFS } from "@wasmer/wasi";

306

307

await init();

308

309

// Set up filesystem before WASI execution

310

const fs = new MemFS();

311

fs.createDir("/input");

312

fs.createDir("/output");

313

314

// Create input files

315

const inputFile = fs.open("/input/data.txt", {

316

write: true,

317

create: true

318

});

319

inputFile.writeString("Processing this data...\n");

320

321

// Configure WASI with custom filesystem

322

const wasi = new WASI({

323

args: ["processor", "/input/data.txt", "/output/result.txt"],

324

fs: fs

325

});

326

327

// Run WASI program

328

const module = await WebAssembly.compileStreaming(fetch("processor.wasm"));

329

await wasi.instantiate(module, {});

330

const exitCode = wasi.start();

331

332

// Access results through the same filesystem

333

if (fs.metadata("/output/result.txt")) {

334

const resultFile = fs.open("/output/result.txt", { read: true });

335

const result = resultFile.readString();

336

console.log("Processing result:", result);

337

}

338

```

339

340

### Filesystem Utilities

341

342

Common filesystem operations and patterns.

343

344

**Directory Operations:**

345

346

```typescript

347

// Recursive directory creation

348

function createPath(fs: MemFS, path: string) {

349

const parts = path.split('/').filter(p => p);

350

let current = '';

351

352

for (const part of parts) {

353

current += '/' + part;

354

try {

355

fs.createDir(current);

356

} catch (e) {

357

// Directory might already exist

358

}

359

}

360

}

361

362

// List all files recursively

363

function listAllFiles(fs: MemFS, dir: string = '/'): string[] {

364

const files: string[] = [];

365

const entries = fs.readDir(dir);

366

367

for (const entry of entries) {

368

const fullPath = dir === '/' ? entry.path : `${dir}${entry.path}`;

369

370

if (entry.is_dir) {

371

files.push(...listAllFiles(fs, fullPath));

372

} else {

373

files.push(fullPath);

374

}

375

}

376

377

return files;

378

}

379

```