WebAssembly has a binary format and a text format. The binary format (.wasm) is a compact binary instruction format for a stack-based virtual machine and is designed to be a portable compilation target for other higher-level languages such as C, C++, Rust, C#, Go, Python and many more. The text format (.wat) is a human readable format designed to help developers view the source of an WebAssembly module. The text format can also be used for writing codes that can be compiled to the binary format.
The code below shows an example of the .wat format for multiplying two numbers.
(module
(func $multiply (param $lhs i32) (param $rhs i32) (result i32)
get_local $lhs
get_local $rhs
i32.mul)
(export "multiply" (func $multiply))
)
The WebAssembly Binary Toolkit contains a wat2wasm tool that enables you to compile the text format to the binary format.
wat2wasm wat_multiply.wat
You will get the following .wasm binary format file as output.
wat_multiply.wasm
The source code of the Javascript that loads the .wasm file is illustrated below. Click to see the demo.
fetch('./wat_multiply.wasm').then(response =>
response.arrayBuffer()
).then(bytes => WebAssembly.instantiate(bytes)
).then(results => {
instance = results.instance;
console.log("Multiply Result is " +
instance.exports.multiply(2,5));
}).catch(console.error);