Quick start with JavaScript on WasmEdge

First, let’s build a WebAssembly-based JavaScript interpreter program for WasmEdge. It is based on QuickJS with WasmEdge extensions, such as network sockets and Tensorflow inference, incorporated into the interpreter as JavaScript APIs. You will need to install Rust to build the interpreter.

If you just want to use the interpreter to run JavaScript programs, you can skip this section. Make sure you have installed Rust and WasmEdge.

Fork or clone the wasmedge-quickjs Github repository to get started.

  1. git clone https://github.com/second-state/wasmedge-quickjs

Following the instructions from that repo, you will be able to build a JavaScript interpreter for WasmEdge.

  1. # Install GCC
  2. sudo apt update
  3. sudo apt install build-essential
  4. # Install wasm32-wasi target for Rust
  5. rustup target add wasm32-wasi
  6. # Build the QuickJS JavaScript interpreter
  7. cargo build --target wasm32-wasi --release

The WebAssembly-based JavaScript interpreter program is located in the build target directory. You can now try a simple “hello world” JavaScript program (example_js/hello.js), which prints out the command line arguments to the console.

  1. import * as os from 'os';
  2. import * as std from 'std';
  3. args = args.slice(1);
  4. print('Hello', ...args);
  5. setTimeout(() => {
  6. print('timeout 2s');
  7. }, 2000);

Run the hello.js file in WasmEdge’s QuickJS runtime as follows.

  1. $ cd example_js
  2. $ wasmedge --dir .:. ../target/wasm32-wasi/release/wasmedge_quickjs.wasm hello.js WasmEdge Runtime
  3. Hello WasmEdge Runtime

Note: the --dir .:. on the command line is to give wasmedge permission to read the local directory in the file system for the hello.js file. We will use --dir .:. in the following sections.

Make it faster

WasmEdge provides a wasmedgec utility to compile and add a native machine code section to the wasm file. You can use wasmedge to run the natively instrumented wasm file to get much faster performance.

  1. wasmedgec ../../target/wasm32-wasi/release/wasmedge_quickjs.wasm wasmedge_quickjs.wasm
  2. wasmedge --dir .:. wasmedge_quickjs.wasm hello.js

Next, we will discuss more advanced use case for JavaScript in WasmEdge.