Nodejs运行Golang生成的WASM错误但浏览器成功

问题描述 投票:0回答:1

我创建了一个 go 文件作为 WASM:

package main

func main() {
    println("Hello, world!")
}

然后,执行以下命令生成

test.wasm

> GOOS=js GOARCH=wasm go build -o test.wasm ./test.go

我想在 Node.js 中运行 WASM,参考 Node.js with WebAssembly:

// test.js
const fs = require('fs');

const wasmBuffer = fs.readFileSync('./test.wasm');
WebAssembly.instantiate(wasmBuffer).then((wasmModule) => {
  console.log(wasmBuffer);
});

错误信息:

node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[TypeError: WebAssembly.instantiate(): Imports argument must be present and must be an object]

但是,我可以在浏览器中执行:

<html>  
    <head>
        <meta charset="utf-8"/>
        <script src="wasm_exec.js"></script>
        <script>
    if (!WebAssembly.instantiateStreaming) {
      // polyfill
      WebAssembly.instantiateStreaming = async (resp, importObject) => {
            const source = await (await resp).arrayBuffer();
            return await WebAssembly.instantiate(source, importObject);
        };
        }

        const go = new Go();

        let mod, inst;

        WebAssembly.instantiateStreaming(fetch("test.wasm"), go.importObject).then(
        async (result) => {
            mod = result.module;
            inst = result.instance;

            await go.run(inst);
            inst = await WebAssembly.instantiate(mod, go.importObject); // reset instance
        }
        );

        </script>
    </head>
    <body></body>
</html>  


环境:

  • Nodejs:16.15.1
  • Golang:go1.18.3 darwin/arm64
node.js go webassembly
1个回答
4
投票

终于找到了在 Node.js 上执行 Golang WASM 的方法:

// commend the block avoid deadlock
// if (code === 0 && !go.exited) {
//   // deadlock, make Go print error and stack traces
//   go._pendingEvent = { id: 0 };
//   go._resume();
// }

// below code is to avoid deadlock
const result = globalThis[func](...funcArgs);

console.log(result);
process.exit();

或者你可以使用tinyGo编译wasm。


节点和浏览器通用

cross-wasm

© www.soinside.com 2019 - 2024. All rights reserved.