Tuesday, November 22, 2022

Server side WebAssembly - Compile Rust program to WASM and run in console command window

This is a simple post about WebAssembly running on the server or as a console application. The concept of running WebAssembly on the server is expected to revolutionize server-side application development like how JavaScript came to ServerSide via Node.js

Context

We are not going to directly write the program in WebAssembly. The language we are writing the program is Rust. It is a promising language for high-performance computing applications. This post is not going to look at the Rust language aspects instead just writing a simple hello world program in Rust and compiling it to WebAssembly than native binary format.

Environment setup - Windows

We need to install the Rust compiler toolchain. It can be directly installed from the official Rust site via an installer.
Then we need the compilation extension that produces the WebAssembly file (.WASM extension) at the end of the compilation. In Rust terminology, it is called 'target' and the target for WASM can be installed using the below command

rustup target add wasm32-wasi

Now we need an editor. Currently, the entire development community agrees on VS Code as the default code editor so let us keep using it.

The last thing we need to install is the runtime for WebAssembly. As we know WebAssembly is not machine byte code. It's near binary intermediate format. So it requires a runner application that translates WebAssembly instructions into native machine language. It can be easily related to JVM for Java and the CLR for .Net. We will be using Wasmtime for running the WebAssmbly file.

Compiling and running

Below goes the compilation command
rustc program.rs --target wasm32-wasi

This will produce a program.wasm file. To run the file for console output, use the below command.
wasmtime program.wasm

Remember Javac Program.java and Java Program days. It is similar. We should be very unlucky to encounter any errors in the above steps. However, there is a GitHub repo available with simple Rust source code and commands.

https://github.com/joymon/wasm-console-rust

No comments: