WebAssembly (WASM) for High Performance Apps · Урок

Работа с файловой системой WASI

Узнайте, как WASI предоставляет изолированному модулю доступ к файловой системе хоста через предварительно открытые каталоги и доступ к файлам на основе разрешённых возможностей.

Урок 4 из 413 шагов

«Работа с файловой системой WASI» — бесплатный урок WebAssembly (WASM) for High Performance Apps на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения WebAssembly (WASM) for High Performance Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс WebAssembly (WASM) for High Performance Apps содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why Files Need Special Handling

A WASM module has no ambient authority — it cannot open any file by default. WASI grants file access only through preopened directories handed to the module at startup.

  • No path traversal outside what was granted
  • Access is capability-based, not permission-based

Preopened Directories

When a runtime launches a module it can map a host folder to a guest path. The module receives a file descriptor for each mapping.

Example with wasmtime: wasmtime --dir=. app.wasm grants the current directory.

wasmtime run --dir=./data app.wasm

Reading a File from WASI

In a WASI language SDK the standard library file APIs are wired to WASI calls. In C, fopen works only for preopened paths.

#include <stdio.h>
int main() {
  FILE *f = fopen("data/hello.txt", "r");
  if (!f) { perror("open"); return 1; }
  char buf[128];
  while (fgets(buf, sizeof buf, f)) fputs(buf, stdout);
  fclose(f);
  return 0;
}

Writing Files Safely

Writing also requires a preopened directory with the right rights. Attempting to write outside it returns an error such as ENOTCAPABLE.

#include <stdio.h>
int main() {
  FILE *f = fopen("data/out.txt", "w");
  if (!f) return 1;
  fputs("written via WASI\n", f);
  fclose(f);
  return 0;
}

File Descriptors & Rights

Each WASI file descriptor carries a set of rights (read, write, seek, etc.). A directory descriptor can be more restrictive than its host counterpart, enabling least-privilege design.

Path Resolution Rules

WASI resolves paths relative to a preopened descriptor. The runtime picks the longest matching preopen. There is no global root; / is meaningless unless mapped.

The wasi-libc Layer

Languages like C compiled with wasi-sdk use wasi-libc, which translates POSIX calls into WASI syscalls. This is why familiar APIs just work inside the sandbox.

clang --target=wasm32-wasi -o app.wasm app.c

Listing a Directory

Directory iteration uses fd_readdir under the hood. High-level languages expose this as normal directory listing once a directory is preopened.

Common Errors

Typical filesystem errors when learning WASI:

  • ENOENT — file not found within the preopen
  • ENOTCAPABLE — path is outside any granted directory
  • EACCES — descriptor lacks the required right

Multiple Preopens

You can grant several directories, each with a distinct guest alias.

wasmtime run --dir=./in::input --dir=./out::output app.wasm

Best Practices

Grant the narrowest directory possible, prefer read-only preopens, and never assume host absolute paths exist inside the module.

Quick Check

Test your understanding of WASI file access.

Recap

You learned that WASI uses preopened directories and capability-based descriptors to expose files safely. Paths resolve relative to preopens, rights enforce least privilege, and wasi-libc bridges POSIX APIs to WASI syscalls.

Можно начать бесплатно

Изучай WebAssembly (WASM) for High Performance Apps с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

Часто задаваемые вопросы

Урок «Работа с файловой системой WASI» бесплатный?

Да — полный текст урока «Работа с файловой системой WASI» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс WebAssembly (WASM) for High Performance Apps, подпишись на CoddyKit PRO. Курс WebAssembly (WASM) for High Performance Apps содержит 4 уроков всего.

Чему я научусь в уроке «Работа с файловой системой WASI»?

Узнайте, как WASI предоставляет изолированному модулю доступ к файловой системе хоста через предварительно открытые каталоги и доступ к файлам на основе разрешённых возможностей. Ты практикуешь WebAssembly (WASM) for High Performance Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать WebAssembly (WASM) for High Performance Apps?

Предыдущий опыт не требуется. WebAssembly (WASM) for High Performance Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Работа с файловой системой WASI»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке WebAssembly (WASM) for High Performance Apps?

Да. Каждый урок WebAssembly (WASM) for High Performance Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Введение в WASI и его цели
  2. Создание и запуск модулей WASI
  3. Возможности WASI и перспективы
  4. Работа с файловой системой WASI
← Назад к WebAssembly (WASM) for High Performance Apps