Skip to content

Instantly share code, notes, and snippets.

@eser
Last active September 13, 2023 16:49
Show Gist options
  • Save eser/b68fc3aa76859c535c9901db630bd2a4 to your computer and use it in GitHub Desktop.
Save eser/b68fc3aa76859c535c9901db630bd2a4 to your computer and use it in GitHub Desktop.
Universal WASM Loader
export const getWasmCode = async (url) => {
switch (url.protocol) {
case "file:":
const assemblyUrl = url.pathname.substr(0, 1) === "/"
? url.pathname.substr(1)
: url.pathname;
if (globalThis.Deno !== undefined) {
return Deno.readFile(assemblyUrl);
}
if (globalThis.process !== undefined) {
const fs = await import("node:fs/promises");
return fs.readFile(assemblyUrl);
}
throw new Error(`Unsupported runtime`);
case "https:":
case "http:":
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(
`Failed to fetch WASM file: ${response.status} ${response.statusText}`,
);
}
return response.arrayBuffer();
default:
throw new Error(`Unsupported protocol: ${url.protocol}`);
}
};
export const getWasmInstance = async (wasmCode) => {
const imports = {
__wbindgen_placeholder__: {},
};
const module = await WebAssembly.instantiate(wasmCode, imports);
return module.instance;
};
export const loadWasm = async (url) => {
const wasmCode = await getWasmCode(url);
const wasmInstance = await getWasmInstance(wasmCode);
return wasmInstance.exports;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment