user12658460
user12658460

Reputation:

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?

SOLUTION:

There was nothing wrong with my code, rather here was something wrong with the way I was compiling my code. Instead of using

em++ test.cpp -o test.wasm

I should've used:

em++ -O1 test.cpp -o test.wasm -s WASM=1

Upvotes: 12

Views: 16330

Answers (4)

Eugene Gr. Philippov
Eugene Gr. Philippov

Reputation: 2092

I was able to get rid of wasi_snapshot_preview1 error by recompiling with flags

emcc test.c -o test.wasm --no-entry -s EXPORTED_FUNCTIONS=_sum

Parameters: --no-entry means no main alike, sum is the function to be exported from test.c.

suggested by (long) blog post [1]

[1] https://habr.com/en/companies/otus/articles/693572/ (In Russian)

Upvotes: 0

Maria
Maria

Reputation: 399

Using this as second argument for WebAssembly instantiate worked for me:

const importObject = { wasi_snapshot_preview1: wasi.exports };
//more code
const instance = await WebAssembly.instantiate(wasm, importObject);

Upvotes: 1

bds
bds

Reputation: 188

Change test.wasm to test.js should work as well:

em++ -O1 test.cpp -o test.js -s WASM=1

Using .wasm as the output type or -s STANDALONE_WASM requires a runtime with wasi_snapshot_preview1 support.

Upvotes: 8

ColinE
ColinE

Reputation: 70122

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.

Upvotes: 2

Related Questions