Instantiating a Wasm module with Node.js

The Wasm files are instantiated in /src/load-assets.js. We're using the memory.wasm file from Cook the Books, but the /assets/main.wasm file is compiled from a slightly different version of main.c, which is located in the /lib folder. The loadWasm() function performs the same operation as the Wasm initialization code from Cook the Books, but the method for passing in the bufferSource to WebAssembly.instantiate() is different. Let's examine this further by reviewing a portion of the code in the loadWasm() function of the load-assets.js file:

const fs = require('fs');
const path = require('path');

const assetsPath = path.resolve(__dirname, 'assets');

const getBufferSource = fileName => {
const filePath = path.resolve(assetsPath, fileName);
return fs.readFileSync(filePath); // <- Replaces the fetch() and .arrayBuffer()
};

// We're using async/await because it simplifies the Promise syntax
const loadWasm = async () => {
const wasmMemory = new WebAssembly.Memory({ initial: 1024 });
const memoryBuffer = getBufferSource('memory.wasm');
const memoryInstance = await WebAssembly.instantiate(memoryBuffer, {
env: {
memory: wasmMemory
}
});
...

To elaborate on the differences, here's some code that instantiates a module using fetch:

fetch('main.wasm')
.then(response => {
if (response.ok) return response.arrayBuffer();
throw new Error('Unable to fetch WebAssembly file');
})
.then(bytes => WebAssembly.instantiate(bytes, importObj));

When using Node.js, the fetch call is replaced by the fs.readFileSync() function and the arrayBuffer() function is no longer required because fs.readFileSync() returns a buffer that can be passed directly into the instantiate() function. Once the Wasm module is instantiated, we can start interacting with the instance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset