Search code examples
v8webassembly

How to run wasm on d8


I have a wasm file fib.wasm which contains function fib(n). If run it in the browser, we can do

var module, functions = {};
fetch('fib.wasm')
  .then(response => response.arrayBuffer())
  .then(buffer => new Uint8Array(buffer))
  .then(binary => {
    var moduleArgs = {
      wasmBinary: binary,
      onRuntimeInitialized: function () {
        functions.fib =
          module.cwrap('fib',
                       'number',
                       ['number']);
        onReady();
      }
    };
    module = Module(moduleArgs);
  });

If in Node, since fetch is not implemented, we can do

const fs = require('fs')
const buf = fs.readFileSync('fib.wasm')
(async () => { res = await WebAssembly.instantiate(buf); })()
const { fib } = res.instance.exports

However, in d8 shell, both ways involves functions undefined. How can we run wasm in d8?


Solution

  • The d8 shell has a function read() which reads a file from disk. It takes an optional parameter to specify binary mode. So the following should work:

    const buf = read('fib.wasm', 'binary');
    let res;
    WebAssembly.instantiate(buf).then((x) => res = x, (error) => console.log(error));
    const { fib } = res.instance.exports;