Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Run WebAssembly in Node.js using the node-loader


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: 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.

    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.

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

    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.

    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.

    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.