我创建一个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
1条答案
按热度按时间kknvjkwl1#
最后,我找到了一种在Node.js上执行Golang WASM的方法:
更多细节和代码:https://github.com/riskers/nodejs-exec-go-wasm