loading...

Running WASM on node.js

dnafication profile image Dinanath ・2 min read

Getting started with Web Assembly is super easy with SSVM. It allows you compile high performance Rust functions into WebAssembly (wasm file), and call them from Node.js/deno applications. So, you get best of both worlds.

While manual installation has its perks and also headaches, I prefer docker image for quick tests and ssvm is easy to setup in Docker. Ensure you have docker installed to go through following steps.

Steps:

  1. Clone the repo: https://github.com/second-state/rust-wasm-ai-demo
$ git clone https://github.com/second-state/rust-wasm-ai-demo.git
  1. Go into the cloned directory rust-wasm-ai-demo and do the following.
# create the Dockerfile
$ cat >> Dockerfile <<EOL
FROM ubuntu:20.04
ARG DEBIAN_FRONTEND=noninteractive
ENV RUSTUP_HOME=/usr/local/rustup \
    CARGO_HOME=/usr/local/cargo \
    PATH=/usr/local/cargo/bin:$PATH
RUN apt-get update \
    && apt-get install -y tzdata \
    && apt-get -y upgrade && apt-get install -y build-essential curl wget git vim libboost-all-dev
RUN curl -sL https://deb.nodesource.com/setup_14.x |  bash \
    && apt-get install -y nodejs \
    && npm install -y -g ssvmup --unsafe-perm \
    && npm install -y ssvm \
    && npm install express express-fileupload
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
EOL

# build the image
$ docker build -t ssvm-nodejs:v1 .

# run the docker container exposing port 8080 which is 
# where express server is listening. 
# also mounting the current directory to `/app`
$ docker run -p 8080:8080 --rm -it -v $(pwd):/app ssvm-nodejs:v1

## ---------------------------------------- ##

# when you run above command, 
# you will be in the container's shell:

$ cd /app

# build the WASM bytecode 
$ ssvmup build

# install node dependencies
$ cd /app/node
$ npm init -y
$ npm install express express-fileupload

# run the webserver
$ npm start

If all went correctly, you should have a running web server with Image Recognition capability. Point your browser to http://localhost:8080 and enjoy. 😊

Reference Repos:

Posted on by:

dnafication profile

Dinanath

@dnafication

JS developer who enjoys using serverless flavour of delivering solutions.

Discussion

markdown guide