Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 133 ยท The Runtime

WebAssembly in Node.js: Modules, Memory, Imports and Traps

Learn what WebAssembly is, how Node.js loads and runs .wasm modules with the global WebAssembly API, how memory, imports and traps work, and run hand-built modules in the editor.

WebAssembly (Wasm) is a compact binary instruction format that a virtual machine can run at near-native speed, safely, in a sandbox. It began as a way to run C, C++ and Rust code in browsers, and every modern JavaScript engine, including V8 inside Node.js, can run it. You compile source code from another language into a .wasm file, then load that file from JavaScript and call its functions.

Why would a Node.js developer care? Four reasons come up in practice. You can reuse a library written in Rust, C or Go without a native add-on that must be compiled for each operating system. You can run CPU-heavy work (image codecs, parsers, compression, crypto) faster than plain JavaScript. You can run untrusted plug-ins inside a sandbox that has no access to the file system or the network unless you hand it capabilities. And the same .wasm file runs in the browser, on the server and at the edge.

Node.js has the standard WebAssembly object as a global, exactly like the browser. No import and no installation are needed, so every example in this lesson runs in the editor. Because the editor has no compiler toolchain, we assemble the modules ourselves from bytes. That is the best way to see what a Wasm module really is.

Modules, instances and imports

Three words carry most of the vocabulary:

  • A module is the compiled, stateless code. It declares what it imports (things it needs from the host) and what it exports (things the host may use).
  • An instance is a module plus its own state (memory, tables, globals), created by supplying the imports.
  • Imports and exports are the only way in and out. Wasm cannot call console.log, read a file or open a socket on its own; it can only call functions you pass in as imports. That is the sandbox.

Wasm has four value types you can use directly: i32, i64, f32 and f64. There are no strings or objects at the boundary. Anything richer travels through linear memory, a growable array of bytes that both sides can read and write.

Your first module: 41 bytes

This is a complete module that exports one function, add(a, b). The bytes are the binary encoding: a header, then a type section, a function section, an export section and a code section.

Node.js Compile, validate and call a hand-written module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

WebAssembly.validate checks the bytes without running anything, compile produces a module, and instantiate gives you the instance whose exports object holds ordinary JavaScript-callable functions. Numbers cross the boundary as numbers, and an i32 wraps around on overflow instead of becoming a bigger JavaScript number. For i64, JavaScript uses BigInt on both sides.

In real projects you do not write bytes. You compile source code, then load the file:

JavaScript
import { readFile } from 'node:fs/promises';

const bytes = await readFile(new URL('./image-codec.wasm', import.meta.url));
const { instance } = await WebAssembly.instantiate(bytes, { env: { log: console.log } });
console.log(instance.exports.decode(...));

WebAssembly.instantiate(bytes, imports) is the one call you use most: it compiles and instantiates in one step and resolves to { module, instance }.

Imports, memory and traps

A more realistic module shares memory with JavaScript, calls back into JavaScript through an import, and can fail with a trap. The example builds such a module with a tiny assembler, so you can see how the sections fit together. The module imports env.memory and a function env.log(i32), and exports:

  • sumBytes(pointer, length): adds up a range of bytes in memory (a loop, written with block, loop and br_if),
  • logTwice(x): calls the imported log two times,
  • boom(): executes the unreachable instruction, which always traps.
Node.js Shared memory, an import and a trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four lessons are packed into that output.

  1. Memory is shared bytes. JavaScript writes four bytes with a Uint8Array view of memory.buffer; the Wasm function reads them through its pointer and length. This is how strings, images and structs cross the boundary: write the bytes into memory, pass a pointer and a length.
  2. Imports are the only door out. Wasm could only reach console.log because we passed a function. A plug-in sandbox is just a choice of imports.
  3. Growing memory detaches the old buffer. After grow, the previous ArrayBuffer has length 0. Always re-read memory.buffer after any call that might grow memory, rather than keeping an old view.
  4. A trap is an exception. Division by zero, out-of-bounds memory access, unreachable and a few others abort the Wasm call with a WebAssembly.RuntimeError; the instance remains usable.

Tables, globals and what else exists

  • A table is an array of function references, used for function pointers and virtual calls (call_indirect). From JavaScript, new WebAssembly.Table({ initial: 4, element: 'anyfunc' }) creates one that you can fill with exported functions.
  • A global is a typed variable shared between the host and the module (new WebAssembly.Global({ value: 'i32', mutable: true }, 0)).
  • Streaming compile (WebAssembly.compileStreaming, instantiateStreaming) belongs to the Fetch API in browsers; Node.js offers it for Response objects too, though reading the file and calling instantiate is the usual route.
  • Threads and SIMD exist as extensions; garbage-collected languages, exceptions and multiple memories keep arriving in newer engines. Check support for a feature in your Node version before depending on it.

Toolchains: where .wasm files come from

Source language Typical tool Notes
Rust cargo build --target wasm32-unknown-unknown, wasm-bindgen, wasm-pack Best-supported path; bindings generate the string and object glue
C and C++ Emscripten, or clang with --target=wasm32 Emscripten emits a .wasm file and JavaScript glue
Go GOOS=wasip1 GOARCH=wasm go build (or GOOS=js) Larger binaries; TinyGo makes small ones
TypeScript-like AssemblyScript Syntax close to TypeScript, compiles directly to Wasm

Writing the glue by hand is rarely necessary. The generated JavaScript wrapper loads the module, wires imports, and converts strings and arrays to memory writes.

WASI: system access without giving up the sandbox

Plain Wasm cannot read files or print. WASI (the WebAssembly System Interface) defines a standard set of imports for exactly that: arguments, environment, clocks, random numbers and file access, where files are limited to the directories you "pre-open". Node.js includes the node:wasi module to provide those imports to a module compiled with a WASI target. It is still marked experimental in Node's documentation, so check your version before relying on it:

JavaScript
import { WASI } from 'node:wasi';
import { readFile } from 'node:fs/promises';

const wasi = new WASI({
  version: 'preview1',
  args: ['tool', '--verbose'],
  preopens: { '/data': './data' },        // the only host folder the module can see
});

const wasm = await WebAssembly.compile(await readFile('./tool.wasm'));
const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject());
wasi.start(instance);

When Wasm helps, and when it does not

  • It helps for compute-heavy, self-contained work (codecs, parsers, hashing, simulation), for reusing existing C/Rust libraries, and for sandboxing plug-ins.
  • It does not help for code that mostly waits on I/O (the event loop already handles that), for tiny functions (the call across the boundary and the data copying cost something), or for code that manipulates JavaScript objects (strings and objects must be copied into memory).
  • Measure first. V8 optimizes JavaScript very well; compare a realistic workload before moving code to Wasm. If a single call is heavy, a worker thread running the Wasm module keeps the main thread free.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What can a WebAssembly module do without being given any imports?

    Wasm has no ambient access to the host. Everything it can do outside its own memory comes from imports you provide, which is what makes it a sandbox.
  2. 2. How does a string get from JavaScript into a Wasm function?

    Wasm functions take only numbers. Richer data is copied into memory, and the function is told where it is and how long it is.
  3. 3. What happens to an old memory.buffer after memory.grow()?

    Growing may move the memory, so the previous ArrayBuffer is detached. Typed array views made from it stop working.
  4. 4. Which JavaScript type represents Wasm i64 values at the boundary?

    A JavaScript Number cannot hold every 64-bit integer, so i64 values are passed as BigInt.

Summary

  • WebAssembly is a global in Node.js: validate, compile, instantiate, plus Module, Instance, Memory, Table, Global.
  • A module declares imports and exports; an instance adds state. Only values of type i32, i64 (BigInt), f32 and f64 cross the boundary.
  • Strings and structures travel through linear memory as bytes with a pointer and a length; growing memory detaches old buffers.
  • Imports are the only way out, which makes Wasm a good plug-in sandbox; a trap surfaces as WebAssembly.RuntimeError.
  • Real .wasm files come from Rust, C/C++, Go or AssemblyScript; WASI (node:wasi) gives controlled system access.
  • Use Wasm for compute-heavy, self-contained work, and measure before and after.

Next: Buffers and Binary Data.