WebAssembly in Node.js
Node.js is a JavaScript runtime that runs outside the browser. It can load and run the same .wasm module with the same WebAssembly API.
Read the file in Node
Read the .wasm file into a buffer. The buffer holds the module bytes.
import { readFileSync } from "node:fs";
const bytes = readFileSync("add.wasm");Start the module in Node
Pass the bytes to instantiate. Then call the exported add function.
const { instance } = await WebAssembly.instantiate(bytes);
console.log(instance.exports.add(2, 3));The same module, the same call
The browser and Node share the API. So the same add call gives the same answer.
console.log(instance.exports.add(10, 20));Example
(async () => {
const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes);
console.log(instance.exports.add(2, 3));
})();Key points
- Node.js runs JavaScript outside the browser.
- Node reads the .wasm file from the disk.
- WebAssembly.instantiate starts the module in Node too.
- The same exports work the same way in Node.
- The Node.js Beginner course on this site teaches Node itself.
In this example, the bytes are decoded and passed to WebAssembly.instantiate. Then the code calls the exported add function with 2 and 3. That gives 5, just as it does in the browser.
Note
Fetch cannot read a local file, so read the file instead.
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
How does Node.js get the bytes of a .wasm file?