Thank you ColinE. This solved my problem trying to upload a WASM module to NPM. For that, I had to split your answer into two file: 'export' and 'import.' Ignoring browser compatibility and focusing only on Node, my solution ended up like this:
const readFileSync = require('fs').readFileSync
const writeFile = require('fs').writeFileSync;
const wasmCode = readFileSync("./public/wasm/main.wasm");
const encoded = Buffer.from(wasmCode, 'binary').toString('base64');
function exportToJson(encoded){
json = "\""+encoded+"\""
writeFile("b64wasm.json", json, err => {
if (err) {
console.error(err);
}
// file written successfully
});
}
exportToJson(encoded)
and
wasmBin = require("./b64wasm.json")
const crypto = require("crypto").webcrypto;
globalThis.crypto = crypto;
require('./public/wasm/wasm_exec.js');
function decode(encoded) {
var binaryString = Buffer.from(encoded, 'base64').toString('binary');
var bytes = new Uint8Array(binaryString.length);
for (var i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
function loadWebAssembly() {
const go = new Go();
const importObject = go.importObject;
WebAssembly.instantiate(decode(wasmBin), importObject).then((results) => {
const instance = results.instance
go.run(instance);
console.log("arrival One")
});
}
loadWebAssembly()
setTimeout(()=>{
let a = Math.floor(Math.random()*100)
let b = Math.floor(Math.random()*100)
const sum = addTwoNumbers(a,b);
console.log("arrived two: ", sum)
},100)