如何从node.js使用WebAssembly?

时间:2018-07-18 13:30:50

标签: node.js emscripten webassembly

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

我已经使用Emscripten将C代码编译为WebAssembly,但不知道如何进行此操作。

任何在正确方向上的帮助都将非常有用。谢谢!

2 个答案:

答案 0 :(得分:11)

You can build a .wasm file (standalone) without JS glue file. Someone has answered the similar question.

Create a test.c file:

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

Build the standalone .wasm file:

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

Use the .wasm file in Node.js app:

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);
});

The key part is the second parameter of WebAssembly.instantiate(). Without it, you will get the error message:

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

答案 1 :(得分:0)

感谢@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);
});