Running .wasm (WebAssembly) files in Node.js primarily involves several steps:
-
Compile source code to WebAssembly:
Use appropriate tools (e.g., Emscripten or other WebAssembly toolchains) to compile source code (such as C/C++ or Rust) into.wasmfiles. -
Load
.wasmfiles in Node.js:
Use thefsandWebAssemblymodules to read and instantiate.wasmfiles.
Here is a simple example demonstrating how to load and run .wasm files in Node.js:
javascriptconst fs = require('fs'); const path = require('path'); // Assume you have a precompiled `.wasm` file named `example.wasm` const wasmFilePath = path.join(__dirname, 'example.wasm'); // Read the `.wasm` file const wasmBuffer = fs.readFileSync(wasmFilePath); (async () => { // Instantiate the WebAssembly module const wasmModule = await WebAssembly.compile(wasmBuffer); const instance = await WebAssembly.instantiate(wasmModule); // Assuming the WebAssembly module exports a function named `add` // We call this exported function const result = instance.exports.add(1, 2); console.log(`Result: ${result}`); // Output the result })();
In this example, we use the Node.js fs module to synchronously read a file named example.wasm, and the WebAssembly module to asynchronously compile and instantiate it. Assuming the .wasm file exports a function named add, we can directly call it.
Ensure WebAssembly support is enabled in your Node.js environment. Node.js versions 8 and above support WebAssembly.
Additionally, note that when instantiating a WebAssembly module—especially if it has imports (such as memory or tables)—you may need to pass an import object. This object contains JavaScript implementations for all WebAssembly imports required during instantiation. Since the example has no imports, no such object is needed.
To run the above code, ensure you have created a valid .wasm file and set its path to example.wasm, then execute the Node.js script.