🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly WASI: Wasm Outside the Browser

WASI runs WebAssembly outside the browser. WASI is short for WebAssembly System Interface.

Print a line in Rust

This main prints one line and ends.

fn main() {
  println!("Hello from WASI!");
}

Build and run it

Build for wasip1, then run it with Wasmtime.

cargo build --target wasm32-wasip1
wasmtime run target/wasm32-wasip1/debug/hello.wasm

Example

const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {});
  console.log("2 + 3 =", instance.exports.add(2, 3));
})();

Key points

  • WASI is an interface for files, clocks, and standard output.
  • Use Wasmtime to run a WASI module from the command line.
  • Build Rust for the wasip1 target to make a WASI module.
  • The browser loader below cannot run WASI here.
  • The Rust code above is what Wasmtime runs.
  • WASI moves Wasm from the page to the command line.

In this example, the code decodes the module bytes from B64 and instantiates the module. It calls add with 2 and 3 and logs the sum. The browser cannot run WASI, so this loader only proves the module loads.

Note

the run command prints only the program’s own line.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does Wasmtime run?