WebAssembly (WASM)
TL;DR
WebAssembly (Wasm) is a binary instruction format designed as a portable compilation target for programming languages like C, C++, and Rust. Node.js can execute Wasm modules, allowing you to run near-native speed code seamlessly alongside your JavaScript.
Mental Model
How It Works
Wasm was originally designed to run heavy code in the browser, but because Node.js uses the V8 engine, it natively supports Wasm as well.
Unlike Native C++ Addons (which have full OS access and require compiling specific .node files for Windows, Mac, and Linux), Wasm modules are platform-independent binaries. You compile the code once, and it runs anywhere Node.js runs. Furthermore, Wasm runs in a secure sandboxed environment, meaning it cannot access the file system unless you explicitly pass it functions to do so.
Example
const fs = require('fs');
async function runWasm() {
// 1. Read the compiled Wasm binary
const wasmBuffer = fs.readFileSync('math.wasm');
// 2. Instantiate the module in V8
const { instance } = await WebAssembly.instantiate(wasmBuffer);
// 3. Call the highly optimized function written in Rust/C++
const result = instance.exports.add(5, 10);
console.log(`Result from Wasm: ${result}`);
}
runWasm();
Common Interview Questions
WebAssembly vs Native Addons: Which should I use?
- Use WebAssembly if you want portability (compile once, run anywhere), security (sandbox), and near-native speed for CPU-bound math/logic.
- Use Native Addons (C++) if you specifically need to interact directly with the OS, hardware drivers, or existing C libraries that perform heavy I/O.
Is Wasm faster than JavaScript?
For heavy computational tasks (image processing, physics engines), yes, Wasm is significantly faster because it is pre-compiled, strongly typed, and doesn’t require the V8 engine to spend time parsing, interpreting, or garbage collecting. However, for simple tasks or heavy DOM/I/O manipulation, the overhead of crossing the boundary between JS and Wasm can actually make it slower.