Node.js WebAssembly

π Node.js WebAssembly (WASM) Tutorial
WebAssembly (WASM) allows you to run high-performance, low-level code (C, C++, Rust, Go, etc.) inside Node.js with near-native speed.
Node.js supports WebAssembly natively β no browser required.
π§ What isΒ WASMΒ ?
WebAssembly (WASM) is:
A low-level binary format
Fast and optimized for performance
Supported by Node.js and all modern browsers
Ideal for CPU-heavy tasks
Examples where WASM is useful:
Image/Video processing
Crypto operations
Data compression
Game engines
Machine learning
Big mathematical calculations
π₯ Why Use WebAssembly in Node.js?
β C/C++/Rust code running inside Node
β Up to 10xβ100x faster
β Share code between Browser + Server
β Great for microservices needing performance
β Works with Node.js modules
π 1. Running a Simple WebAssembly File in Node.js
Letβs create a very simple WASM module that adds two numbers.
Step 1 β Create a WebAssembly Text File (.wat)
Create a file:add.wat
Step 2 β Convert .wat β .wasm
Install wabt tools:
Compile:
Step 3 β Load WASM in Node.js
Create index.js:
Run:
Output:
π You just ran WebAssembly inside Node.js!
π 2. Using Rust with WebAssembly in Node.js
Rust is the best language for producing WebAssembly.
Install WASM tools:
Create project:
Edit src/lib.rs
Build WASM:
Youβll get a /pkg folder with WASM + JS bindings.
Use in Node.js:
Create test.js:
Run:
π 3. Using C/C++ with WebAssembly (Emscripten)
Install Emscripten:
Create add.c
Compile to WASM:
Node.js Example:
π§© Calling JavaScript from WASM and vice-versa
You can pass:
Numbers
Arrays
Memory buffers
Strings
Example JS β WASM:
Example WASM β JS:
βοΈ 4. Node.js + WebAssembly Performance Use Cases
π High-Performance Microservices
Example tasks ideal for WASM:
Encryption (SHA-256, AES)
Image resizing
PDF processing
Data compression (gzip, brotli)
Video transcoding
AI model inference
π§± 5. WASI in Node.js
Node.js supports WASI, allowing WASM modules to access:
File system
OS
Network
Environment variables
Install WASI:
Example:
π¦ 6. Loading WebAssembly Dynamically
π 7. Real-World Projects
| Project | Purpose |
|---|---|
| FFmpeg WASM | Video processing |
| Squoosh | Image compression |
| SQLite WASM | Database in WASM |
| Blazor | .NET in the browser |
| TensorFlow WASM | Machine Learning |
π Conclusion
Node.js + WebAssembly gives you:
β‘ Near-native performance
π§± Ability to run C, C++, Rust in Node.js
π Secure sandbox execution
π Same WASM runs in Browser + Node
π Perfect for heavy computations
