Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
WASM Rust to Node Example

WASM Rust to Node Example

Use only > 8.x.x NodeJS version

Install Rust before using this tutorial: curl -sSf | sh

Create dirs:

mkdir wasmRustNodeExample

cd wasmRustNodeExample

mkdir Node

Create Rust Library:

cargo new Rust --lib

cd Rust

Change ./src/ file:

pub fn add(a: i32, b: i32) -> i32 {
    a + b

Next, change the crate type to cdylib. Add this to your Cargo.toml:

name = "Rust"
version = "0.1.0"

path = "src/"
crate-type = ["cdylib"]

Install the latest nightly (2017-11-25 or later):

rustup toolchain install nightly

Install the required target:

rustup target add wasm32-unknown-unknown --toolchain nightly

Finally, compile it:

cargo +nightly build --target wasm32-unknown-unknown --release && cp target/wasm32-unknown-unknown/release/deps/*.wasm ../Node/

Install node dependencies:

cd ../Node

npm init

npm i fs --save

Create main.js file:

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);

Run Node:

node main.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment