Learning WebAssembly #6: Running Wasm in Node.js

Running Wasm code in Node.js, the popular backend platform.


In the previous part of this series, we have executed Wasm modules in a browser. In this part, we will achieve the same in Node.js, a popular JavaScript backend platform.

Starting with version 12, Node.js provides an implementation of the WASI API, WebAssembly System Interface. WASI gives sandboxed WebAssembly applications access to the underlying operating system features. In the following text, we will focus only on basic Wasm, WASI will be discussed in a dedicated future post.

Wasm Module Initializing

Practically, Node.js provides a global WebAssembly object, which we already know from WebAssembly JavaScript API.

There are some little differences though. For example, the convenience static method instantiateStreaming is missing whatsoever. The reason is quite clear: the method accepts an interface from the Fetch API, which is not provided by Node.js out of the box.

Instead, we can use the instantiate method which accepts an ArrayBuffer:

var buf = fs.readFileSync('./hello.wasm');
WebAssembly.instantiate(buf)...

The rest is the same as when running in a browser:

WebAssembly
  .instantiate(fs.readFileSync('./hello.wasm'))
  .then(obj => console.log(obj.instance.exports.hello()));

It works on my machine:

$ node --version
v14.15.3

$ node hello.js 
42

Similar for dealing with the memory or global variables. There is no change needed in the actual code except the initialization of a Wasm instance.

Further Steps

We have seen how easy is to work with WebAssembly in Node.js. Except for a little difference in the initialization, all that we have learned so far applies here as well. It’s very good news!

In the next part of this series, we will see how to access operating system features from Wasm with WebAssembly System Interface (WASI).

Stay tuned!