Skip to content

Instantly share code, notes, and snippets.

@ilyakmet
Last active December 19, 2020 17:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ilyakmet/34c15e1c2c43b77f9e5dce902706a6a8 to your computer and use it in GitHub Desktop.
Save ilyakmet/34c15e1c2c43b77f9e5dce902706a6a8 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/

Create main.js file:

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

Run Node:

node main.js
@jrop
Copy link

jrop commented Apr 4, 2019

@ilyakmet Thanks for the writeup! Just FYI, fs is a core NodeJS module, so you don't need to npm i fs.

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