Run WebAssembly in Node.js using the node-loader

Nik Graf
InstructorNik Graf

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 5 years ago

WebAssembly is great for targeting performance bottlenecks in the browser. Now with node-loader, we can do the same on the server through Node.js

While Node offers also bindings to native extensions for C/C++ via node-gyp, there was no straight forward way to write Rust extensions. In addition did the node-gyp API change often and developers had to be careful to make their C/C++ code work with various operating systems.

Compiling Rust to WebAssembly solves both of these issues. The API is stable and once compiled to WebAssembly it will run on every operating system supported by Node.

Since Node doesn't support loading .wasm files a loader is needed. The loader flag though is only supported when using the --experimental-modules flag in Node 10 or higher.

Instructor: [00:00] While using WebAssembly in the browser is great, I'm pretty excited about using it in Node to write performant code without writing C bindings. Let's give it a try.

[00:10] We're going to start with a clean slate, an empty directory, and then run NPM init to initialize that package.json file. Next up, we're going to install the WASM Node loader. Then we'll create a new Rust crate, using cargo new crate. Name it utils, and use the library template for it.

[00:33] In our newly-generated Cargo.toml, we change the crate type to cdylib. Now, we are set to write our Rust code.

[00:45] We'll export a simple addOne function, accepting one parameter and returning the value plus one. Next, we compile our Rust code using cargo build with the WASM target. We will set for the Rust path, now can create our child script entry.

[01:08] In there, we import our addOne function from the compiled utils WebAssembly file. We use the function twice. Once using the argument 2, and the other time using the argument 42. We execute this file, running Node with the experimental modules flag, as well as passing in our Node WASM loader to the loader flag.

[01:34] As expected, we see the values 3 and 43 logged out. Pretty cool. Keep in mind, for a production release, you might want to run your utils.wasm file for wasm-gc before actually shipping it.