Learn how to use WebAssembly modules in Node.js, including how to generate, load, and interact with .wasm binaries.
WebAssembly is a high-performance assembly-like language that can be compiled from various languages, including C/C++, Rust, and AssemblyScript. Currently, it is supported by Chrome, Firefox, Safari, Edge, and Node.js!The WebAssembly specification details two file formats:
A binary format called a WebAssembly Module with a .wasm extension
A corresponding text representation called WebAssembly Text format with a .wat extension
A resizable typed array of references not stored in Memory.
Instance
An instantiation of a Module with its Memory, Table, and variables.
In order to use WebAssembly, you need a .wasm binary file and a set of APIs to communicate with WebAssembly. Node.js provides the necessary APIs via the global WebAssembly object.
Once you have a WebAssembly module, you can use the Node.js WebAssembly object to instantiate it.
ESM
CJS
// Assume add.wasm file exists that contains a single function adding 2 provided argumentsimport fs from 'node:fs/promises';// Use readFile to read contents of the "add.wasm" fileconst wasmBuffer = await fs.readFile('/path/to/add.wasm');// Use the WebAssembly.instantiate method to instantiate the WebAssembly moduleconst wasmModule = await WebAssembly.instantiate(wasmBuffer);// Exported function lives under instance.exports objectconst { add } = wasmModule.instance.exports;const sum = add(5, 6);console.log(sum); // Outputs: 11
// Assume add.wasm file exists that contains a single function adding 2 provided argumentsconst fs = require('node:fs');// Use the readFileSync function to read the contents of the "add.wasm" fileconst wasmBuffer = fs.readFileSync('/path/to/add.wasm');// Use the WebAssembly.instantiate method to instantiate the WebAssembly moduleWebAssembly.instantiate(wasmBuffer).then(wasmModule => { // Exported function lives under instance.exports object const { add } = wasmModule.instance.exports; const sum = add(5, 6); console.log(sum); // Outputs: 11});
WebAssembly modules cannot directly access OS functionality on their own. A third-party tool Wasmtime can be used to access this functionality. Wasmtime utilizes the WASI API to access the OS functionality.