Reader small image

You're reading from  Modern Frontend Development with Node.js

Product typeBook
Published inNov 2022
Reading LevelExpert
PublisherPackt
ISBN-139781804618295
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Florian Rappl
Florian Rappl
author image
Florian Rappl

Florian Rappl is a solution architect working on distributed web applications for digital transformation and IoT projects. His main interest lies in the implementation of micro frontends and their impact on teams and business models. As the lead architect he helped to create outstanding web applications for many industry leading companies. He regularly gives lectures on software design patterns and web development. Florian won multiple prizes for his work over the years and is recognized as a Microsoft MVP for development technologies. He started his career in software engineering before studying physics and helping to build an energy-efficient supercomputer. Florian currently lives in Munich, Germany, with his wife and two daughters.
Read more about Florian Rappl

Right arrow

Integrating Native Code with WebAssembly

The whole point of actually using Node.js is convenience. Node.js never aspired to be the fastest runtime, the most complete one, or the most secure one. However, Node.js established a quick and powerful ecosystem that was capable of developing a set of tools and utilities to actually empower the web development standards that we are all used to today.

With the growth of Node.js, the demand for more specialized systems also increased. The rise of new runtimes that offered alternatives to Node.js actually resulted from this need. An interesting alternative can be found in the WebAssembly language. WebAssembly is a portable binary-code format like the Java Virtual Machine (JVM) or the Microsoft Intermediate Language (MSIL). This makes it a potential compilation offering for any language – especially lower-level languages such as C or Rust.

In this chapter, you’ll learn what WebAssembly has to offer, how you can integrate existing...

Technical requirements

The complete source code for this chapter is available at https://github.com/PacktPublishing/Modern-Frontend-Development-with-Node.js/tree/main/Chapter10.

The CiA videos for this chapter can be accessed at https://bit.ly/3DPH53P.

Advantages of using WebAssembly

WebAssembly (WASM) is a language without any runtime. Any kind of functionality – from allocating some memory to making an HTTP request – needs to be integrated by the consuming application. There are, however, some emerging standards such as the WebAssembly System Interface (WASI) that aim to bring a set of standard functionalities to any platform. This way, we can write platform-independent applications using WASM, with a runner integrating WASI.

WASI specification

The WASI specification covers everything that is needed to run WASM outside of a browser. Popular WASM runtimes such as Wasmtime or Wasmer implement WASI to actually run WASM applications. WASI specifies how system resources can be accessed by WASM. As a result, besides having WASI implemented in the runtime, the executed WASM code also needs to know (and use) the API provided by WASI. More details can be found at https://wasi.dev/.

Consequently, one of the advantages...

Running WASM in Node.js

Node.js has a direct integration of WASM via the WASM object. The API is exactly the same as in the browser, allowing us to potentially share the code between Node.js and browsers to integrate a compiled WASM file.

There are three functions in the API of WASM. We can compile an existing binary, transforming it into a WASM runtime module. This module can then be activated using the instantiate method. We can also validate an existing binary – to check whether a given file is indeed a valid WASM binary. All methods are asynchronous and return Promise.

Let’s see an example using a WASM binary, sum.wasm, which exports a single function (sum) and adds two numbers together:

app.mjs

import{ readFile } from 'fs/promises';
const content = await readFile('./sum.wasm');
const wasm = await WebAssembly.compile(content);
const instance = await WebAssembly.instantiate(wasm);
const { sum } = instance.exports;
console.log(sum(2,...

Writing WASM with AssemblyScript

While there are many options to actually generate valid WASM, one of the most attractive ways is to use AssemblyScript. AssemblyScript is a language that looks and feels quite similar to TypeScript, making it rather easy to learn from a syntax perspective. Under the hood, however, there are still some concepts relating to WASM that need to be known in order to write mid-sized to larger AssemblyScript applications or libraries.

One of the core concepts of AssemblyScript is to model the different data types used in WASM. For instance, using integers requires the use of the i32 type.

Let’s have a look at some example code. We’ll start with a small function that expects two parameters, adds them up, and returns the result:

module.ts

export function sum(a: i32, b: i32): i32 {
  return a + b;
}

With the exception of the i32 type, everything in the preceding example looks and feels just like TypeScript. Even the file...

Summary

In this chapter, you extended your knowledge of potential source code files running in Node.js. You are now familiar with running WASM – a lower-level portable binary-code language that can be used as a compilation target by many programming languages.

WASM can help you to write functionality once and run it on multiple platforms. Since WASM can be sandboxed very well, it is a good contender for the next wave of containerized computing, where performance and security are valued highly. You now know how to write WASM using AssemblyScript. You are also empowered to integrate created WASM modules in Node.js.

In the next and final chapter, we will take a look at the use of JavaScript beyond Node.js. We’ll see that other runtimes exist, which are partially compatible with the Node.js ecosystem – providing a great drop-in replacement that can be handy for multiple use cases.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Modern Frontend Development with Node.js
Published in: Nov 2022Publisher: PacktISBN-13: 9781804618295
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Florian Rappl

Florian Rappl is a solution architect working on distributed web applications for digital transformation and IoT projects. His main interest lies in the implementation of micro frontends and their impact on teams and business models. As the lead architect he helped to create outstanding web applications for many industry leading companies. He regularly gives lectures on software design patterns and web development. Florian won multiple prizes for his work over the years and is recognized as a Microsoft MVP for development technologies. He started his career in software engineering before studying physics and helping to build an energy-efficient supercomputer. Florian currently lives in Munich, Germany, with his wife and two daughters.
Read more about Florian Rappl