This is a simple example of compiling and running the WebAssembly textual format (wast) in Node.js on Linux. This does not cover compiling from a higher level language to WebAssembly (for that you probably want Emscripten). But if all you want to do is play around directly with the wast textual format, this should get you going quickly.
- 6-part illustrated intro to WebAssembly: https://hacks.mozilla.org/2017/02/a-cartoon-intro-to-webassembly/
- WebAssembly Text Format: https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format
- Detailed Intro to WebAssembly: https://rsms.me/wasm-intro
-
Install node 8
-
You need a wast to wasm compiler. The are several options. This example uses wabt (wabbit). You will need a standard gcc toolchain to build wabt. Build wabt and add it to your path:
git clone --recursive https://github.com/WebAssembly/wabt/
cd wabt
make gcc-release
export PATH=`pwd`/out/gcc/Release
Compile a wast to wasm (binary module):
wast2wasm addTwo.wast -o addTwo.wasm
Run an exported function in the wasm binary module using the
runwasm.js
script (this should print 5 to the console):
node ./runwasm.js addTwo.wasm addTwo 2 3
The runwasm.js
script is also written to be used as a node module:
node
> w = require('./runwasm.js')
> w.loadWebAssembly('addTwo.wasm').then(i => console.log(i.exports.addTwo(7,8)))
15
You are free to use runwasm.js
code under an MIT license.
You can also run wasm modules using wac (WebAssembly in C). wac is a WebAssembly interpreter in which the code runs in a native x86 host context rather than in a JavaScript/Web host context.
wac addTwo.wasm addTwo 2 3
0x5:i32