Running a .wasm file in node.js

I've read many articles about running wasm files in node.js. Whenever I test the code, It throws this error

[TypeError: WebAssembly.instantiate(): Import #0 module="wasi_snapshot_preview1" error: module is not an object or function]

and then it does not show anything in the result. I am using this code:

const sp = {
  env: {
    memoryBase: 0,
    tableBase: 0,
    memory: new WebAssembly.Memory({
      initial: 256
    }),
    table: new WebAssembly.Table({
      initial: 0,
      element: 'anyfunc'
    })
  },
  imports: {
    imported_func: arg => {
      console.log(arg);
    }
  }
}

const fs = require('fs')
, wasm = WebAssembly.instantiate(new Uint8Array(fs.readFileSync('./test.wasm')), sp)
.then(result => console.log(result));

This code is throwing the above error.

Is there anything I am doing wrong?

1 answer

  • answered 2020-01-14 06:09 ColinE

    The error reported is as follows:

    [TypeError: WebAssembly.instantiate(): Import #0 module="wasi_snapshot_preview1" error: module is not an object or function]

    This indicates that your WebAssembly module, test.wasm, is expecting an import named wasi_snapshot_preview1, which is required in order to instantiate it. This is nothing to do with the Node environment, you would see the same error in the browser.

    How are you building and compiling your WebAssembly module? This import suggests you are using WASI.

    I would recommend starting with a much simpler WebAssembly example.