What is Wasm or WebAssembly ? Learn WebAssembly Basics with Rust Part B

  • Updated : 02-07-2024 20:20
  • By : Phosphataz
  • Resume

    In the Part A post :

    • - we created a rust library and compiled it to wasm file
    • - we created an html file index.html and integrated a small script tag to fetch the wasm file
    • - then we access to the method inside wasm file or module through JavaScript.


    In this chapter we will see another method of using WebAssembly that is : Running WebAssembly module on the server or the machine directly.


    What is WebAssembly runtime ?


    Runtime software in general is a software that help to execute a program in an environment it create for. It act as virtual machine.

    WebAssembly runtime help to execute a wasm binary file. For example browser is a WebAssembly runtime.

    Beside in the browser, WebAssembly module can also run on :

    • - the systems : using WebAssembly runtime software such us : Wasmer, Wasmetime, wasm3.
    • - embedded systems, IoT : using dedicated WebAssembly embedded runtime : wasm3, WamR.


    Let see how to run wasm file on the system using popular runtime


    How to run WebAssembly binary file on Wasmer runtime ?


    To run WebAssembly binary file on wasmer runtime :

    1 - Installer wasmer

    curl https://get.wasmer.io -sSfL | sh
    


    2 - Create a wasme binary file (go to step 3 if you already have a .wasm binary file)

    • - we will generate wasm binary file from Rust program. So create a rust program :
    • install rust and create a program with cargo :
    cargo new hello
    
    • - locate the main.rs file, you will see the main function that will print hello world on terminal.
    • - you can it with this command :
    cargo run
    
    • Install wasm32-wasi target. This will help us generate wasm file from rust code.
    rustup target add wasm32-wasi
    


    To create a wasm binary file, very simple :

    • - From the project root directory, run this command below to generate the .wasm binary file :
    cargo build --target=wasm32-wasi
    


    • - Then go inside the target/wasm32-wasi/debug folder to see the .wasm file.
    cd target/wasm32-wasi/debug
    


    3 - Run the WebAssembly file with wasmer runtime :

    To run the wasm binary file, from inside target/wasm32-wasi/debug, run the command below :

    wasmer run hello.wasm
    

    Make sure to replace hello.wasm by the name of the generated .wasm binary file in your case.

    Wasmer will decode, compile and run the .wasm binary file and output the "hello world" message of the original Rust program.


    Conclusion


    In this second article we saw how to create a wasm binary from rust program and run it with wasmer runtime.

    Useful links :

    Part A

    Wasmer runtime cli