Skip to content

Instantly share code, notes, and snippets.

@berkus
Forked from ilyakmet/wasmRustNodeExample.md
Created April 4, 2019 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berkus/af490c2c4ba78382cdbaa4f22350821f to your computer and use it in GitHub Desktop.
Save berkus/af490c2c4ba78382cdbaa4f22350821f to your computer and use it in GitHub Desktop.
WASM Rust to Node Example

WASM Rust to Node Example

Use only > 8.x.x NodeJS version

Install Rust before using this tutorial: curl https://sh.rustup.rs -sSf | sh

Create dirs:

mkdir wasmRustNodeExample

cd wasmRustNodeExample

mkdir Node

Create Rust Library:

cargo new Rust --lib

cd Rust

Change ./src/lib.rs file:

#[no_mangle]
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

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

[package]
name = "Rust"
version = "0.1.0"

[lib]
path = "src/lib.rs"
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