Use only > 8.x.x NodeJS version
Install Rust before using this tutorial:
curl https://sh.rustup.rs -sSf | sh
mkdir wasmRustNodeExample
cd wasmRustNodeExample
mkdir Node
cargo new Rust --lib
cd Rust
#[no_mangle]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
[package]
name = "Rust"
version = "0.1.0"
[lib]
path = "src/lib.rs"
crate-type = ["cdylib"]
rustup toolchain install nightly
rustup target add wasm32-unknown-unknown --toolchain nightly
cargo +nightly build --target wasm32-unknown-unknown --release && cp target/wasm32-unknown-unknown/release/deps/*.wasm ../Node/
cd ../Node
touch main.js
Inser code:
const fs = require('fs');
const wasmBufCode = fs.readFileSync('./Rust.wasm');
const wasmModule = new WebAssembly.Module(wasmBufCode);
const wasmInstance = new WebAssembly.Instance(wasmModule, []);
const add = (a, b) => {
console.log(wasmInstance.exports.add(a, b));
};
add(1, 2);
node main.js
@ilyakmet Thanks for the writeup! Just FYI,
fs
is a core NodeJS module, so you don't need tonpm i fs
.