Running WASM in Node.js
Node.js has a direct integration of WASM via the WASM
object. The API is exactly the same as in the browser, allowing us to potentially share the code between Node.js and browsers to integrate a compiled WASM file.
There are three functions in the API of WASM
. We can compile an existing binary, transforming it into a WASM runtime module. This module can then be activated using the instantiate
method. We can also validate an existing binary – to check whether a given file is indeed a valid WASM binary. All methods are asynchronous and return Promise
.
Let’s see an example using a WASM binary, sum.wasm
, which exports a single function (sum
) and adds two numbers together:
app.mjs
import{ readFile } from 'fs/promises';
const content = await readFile('./sum.wasm');
const wasm = await WebAssembly.compile(content);
const instance = await WebAssembly.instantiate(wasm);
const { sum } = instance.exports;
console.log(sum(2,...