如何使用来自 node.js 的 WebAssembly?

How to use WebAssembly from node.js?

我目前正在从事个人 Node.js (>=8.0.0) 项目,该项目需要我调用 C 子例程(以缩短执行时间)。我正在尝试使用 WebAssembly 来执行此操作,因为我需要我的最终代码在浏览器中打开时兼容。

我已经用Emscripten把C代码编译成WebAssembly了,后面不知道怎么进行。

任何方向正确的帮助都会很棒。谢谢!

您可以构建一个 .wasm 文件 (standalone) without JS glue file. Someone has answered the similar .

创建一个 test.c 文件:

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

构建独立的 .wasm 文件:

emcc test.c -O2 -s WASM=1 -s SIDE_MODULE=1 -o test.wasm

在Node.js应用中使用.wasm文件:

const util = require('util');
const fs = require('fs');
var source = fs.readFileSync('./test.wasm');
const env = {
    memoryBase: 0,
    tableBase: 0,
    memory: new WebAssembly.Memory({
      initial: 256
    }),
    table: new WebAssembly.Table({
      initial: 0,
      element: 'anyfunc'
    })
  }

var typedArray = new Uint8Array(source);

WebAssembly.instantiate(typedArray, {
  env: env
}).then(result => {
  console.log(util.inspect(result, true, 0));
  console.log(result.instance.exports._add(9, 9));
}).catch(e => {
  // error caught
  console.log(e);
});

关键部分是WebAssembly.instantiate()的第二个参数。没有它,您将收到错误消息:

TypeError: WebAssembly Instantiation: Imports argument must be present and must be an object at at process._tickCallback (internal/process/next_tick.js:188:7) at Function.Module.runMain (module.js:695:11) at startup (bootstrap_node.js:191:16) at bootstrap_node.js:612:3

谢谢@sven。 (仅翻译)

test.c:

#include <emscripten/emscripten.h>

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

正在编译:

emcc test.c -O2 -s WASM=1 -s SIDE_MODULE=1 -o test.wasm

test.js:

const util = require('util');
const fs = require('fs');
var source = fs.readFileSync('./test.wasm');
const env = {
  __memory_base: 0,
  tableBase: 0,
  memory: new WebAssembly.Memory({
    initial: 256
  }),
  table: new WebAssembly.Table({
    initial: 0,
    element: 'anyfunc'
  })
}

var typedArray = new Uint8Array(source);

WebAssembly.instantiate(typedArray, {
  env: env
}).then(result => {
  console.log(util.inspect(result, true, 0));
  console.log(result.instance.exports._add(10, 9));
}).catch(e => {
  // error caught
  console.log(e);
});