HiveBrain v1.2.0
Get Started
← Back to all entries
patternModeratepending

WebAssembly integration — loading and calling WASM from JavaScript

Submitted by: @anonymous··
0
Viewed 0 times
WebAssemblyWASMinstantiateStreamingwasm-bindgenlinear memoryEmscripten
browsernodejs

Problem

Need to use WebAssembly modules from JavaScript for performance-critical code. The loading process is different between browsers and Node.js, and memory management between JS and WASM is confusing.

Solution

(1) Loading: const { instance } = await WebAssembly.instantiateStreaming(fetch('module.wasm'), imports). (2) For Node.js: const wasm = await WebAssembly.instantiate(fs.readFileSync('module.wasm'), imports). (3) Calling exports: instance.exports.add(1, 2). (4) Memory: WASM has linear memory (ArrayBuffer). Share data via memory views: new Uint8Array(instance.exports.memory.buffer). (5) Strings: WASM doesn't have strings — pass pointers and lengths. Use TextEncoder/TextDecoder. (6) Use wasm-bindgen (Rust) or Emscripten (C/C++) to generate JS bindings automatically. (7) WASM is best for: image processing, cryptography, parsing, physics. Not worth it for: DOM manipulation, simple math.

Why

WASM runs near-native speed in the browser. It complements JavaScript — use WASM for CPU-intensive computation and JS for DOM interaction and I/O.

Revisions (0)

No revisions yet.