Getting WebAssembly to run in Node.js (v13)

I ran into errors while trying out WebAssembly instanciation in Node.js v13:

const instance = await WebAssembly.instantiate(wasm)
WebAssembly.instantiate(): Imports argument must be present and must be an object

Similarly, when trying out the example in the documentation for WASI:

const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
const instance = await WebAssembly.instantiate(wasm, importObject);
UnhandledPromiseRejectionWarning: LinkError: WebAssembly.instantiate(): Import #0 module="env" function="memory" error: memory import must be a WebAssembly.Memory object

At least as of Node.js v13.12.0, the solution is to provide a proper importObject (full example):

const fs = require('fs')

const importObject = {
  env: {
    memory: new WebAssembly.Memory({initial:10,maximum:10})
  }
};

(async () => {
  const binary = fs.readFileSync('./add.wasm')
  const wasm = await WebAssembly.compile(binary)
  const instance = await WebAssembly.instantiate(wasm,importObject)
  console.log(instance.exports.add(4,5))
})()
Photo by bruce mars / Unsplash

For reference I generated add.wasm from

// add.c
#include <webassembly.h>

export int add(int a, int b) {
  return a + b;
}

using

wa compile -o add.wasm add.c

where wa is the binary installed by the webassembly package (there are plenty other compilers around).