Nodejs run WASM generated by Golang error but browser success

fdx2calv  于 2023-04-18  发布在  Go
关注(0)|答案(1)|浏览(152)

我创建一个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达尔文/arm64
kknvjkwl

kknvjkwl1#

最后,我找到了一种在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();

更多细节和代码:https://github.com/riskers/nodejs-exec-go-wasm

相关问题