Web Assembly (Wasm) Web Assembly (Wasm)

Running AssemblyScript Wasm in Node

Check out a free preview of the full Web Assembly (Wasm) course:
The "Running AssemblyScript Wasm in Node" Lesson is part of the full, Web Assembly (Wasm) course featured in this preview video. Here's what you'd learn in this lesson:

Jem imports the minusOne function and calls it from the Node REPL. The AssemblyScript loader automatically imports the AssemblyScipt functions from the build directory.

Get Unlimited Access Now

Transcript from the "Running AssemblyScript Wasm in Node" Lesson

>> So we've written our assembly script. We now have a web assembly function. It's being exported. So let's run it. Let's run our web assembly. Fortunately, assembly script does a lot of the heavy lifting for you. It's creates this index.js file. Which automatically imports, everything in the build directory.

[00:00:28] So as we said before, the build directory has, all of the files and source maps, along with it. And it's automatically imported right here, through the build optimized lasme. So if we wanna use it, we can just call it. So let's go ahead and call that now, let's use node to call our function.

[00:00:47] So what I'm going to say is, I'm just gonna run an instance of node, so I'm gonna say node. And I want to import that function we wrote. So I'm gonna say cost, and what do we call it? Minus one and I'm just gonna require that in from the index.js file.

[00:01:18] Alright, so let's go and run that -12 should give me a 1. Congratulation sorry. Clapping, clapping, nice job. You've now written assembly script compile to web assembly and now you're running that web assembly in node. That's pretty cool. And I love that it's just automatic. So every function we export here will end up being required into the index.js.

[00:01:48] And the pull it out and use it. We just require it in. Using web assembly and node is a bit more straightforward because you don't have to fetch the wasum files. You don't have to compile them or anything like that. The assembly script loader does all that work for you.

[00:02:04] All right, we're cruising along now. Let's, get to something. Well, It's a bit more challenging I'll say, because browsers inherently don't have the concept of all of the glue code that is required to run web assembly. We have to import that in which we'll get to a little bit later.

[00:02:31] But remember, Web Assembly is not this native thing that's built into browsers and then implicitly know how to run. What browsers know how to do is execute a wasum file. That's it, but to actually glue that together to make that useful, we have to call it from JavaScript, which we know how to do.

[00:02:49] But that involves writing some glue code to fetch that web assembly, compile it, export those functions, and then once we export those functions, we can use them in JavaScript, which is pretty cool.