由于做sdk,不浪费流量让用户从服务器下载wasm,而是直接打入sdk内部,所以考虑直接将wasm转为buffer数组直接传入
一、方法
现将wasm二进制转为base64,方便代码引入;使用时再将其转为buffer数组。
二、步骤
1. wasm转换base64
直接使用nodejs进行转换,wasm使用的是mdn的示例
const readFileSync = require('fs').readFileSync;
const writeFileSync = require('fs').writeFileSync;
const wasmCode = readFileSync('simple.wasm');
// 将wasm二进制转为base64
const encoded = Buffer.from(wasmCode, 'binary').toString('base64');
// 写入js文件
writeFileSync('simple.wasm.js', `
const WasmStr = "${encoded}";
// base64转为二进制
function base64ToBinary(str) {
if (typeof atob === 'function') {
// this works in the browser
return atob(str)
} else {
// this works in node
return new Buffer(str, 'base64').toString('binary');
}
}
// base64转为buffer数组
export function decodeWasm() {
var binaryString = base64ToBinary(WasmStr);
var bytes = new Uint8Array(binaryString.length);
for (var i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
`);
2. 页面引用
1) 页面使用module方式引入刚刚生成的simple.wasm.js
,将decodeWasm()
的值传入WebAssembly.instantiate
<!doctype html>
<html>
<head><meta charset="utf-8"><title>WASM test</title></head>
<body>
<script type="module">
import { decodeWasm } from './simple.wasm.js'
const importObject = {
my_namespace: {
imported_func: arg => {
console.log(arg);
}
}
};
;(async () => {
const result = await WebAssembly.instantiate(decodeWasm(), importObject)
result.instance.exports.exported_func();
})()
</script>
</body>
</html>