🚀 Supercharge your NodeJS with Rust

Rate this content
Bookmark

Node.js is great - easy to develop, performant, easy to scale. But there are tasks that are less suited for it - heavy computations or data processing. Join me and learn how you can incorporate Rust as well as WebAssembly into Node and JavaScript and take your performance to the next level!

Dmitry Kudryavtsev
Dmitry Kudryavtsev
21 min
20 Jun, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

In this Talk, Dmitry Kudravtsev discusses how to supercharge JavaScript and Node.js using Rust. He introduces NEON, an open-source library for integrating Rust and JavaScript, and explains how to use it to export Rust functions to JavaScript. Dmitry also explores the performance benefits of using native modules written in Rust and WebAssembly. He compares the two approaches and highlights the faster performance of Rust native modules. He concludes by recommending WebAssembly for its ergonomics and portability, while suggesting native modules for extending Node.js with performance code.

Available in Español: 🚀 Potencia tu NodeJS con Rust

1. Introduction to Rust and Node.js

Short description:

Hi, my name is Dmitry Kudravtsev, I'm a senior software engineer passionate about JavaScript and Rust. Today, I want to talk about supercharging your JavaScript and Node.js experience using Rust. Node.js has a great ecosystem, but it can be slow for CPU tasks. Writing native modules in Rust is a solution. Rust is a modern language with better tooling and memory safety compared to C and C++.

Hi, my name is Dmitry Kudravtsev, I'm a senior software engineer and I'm very passionate about two things, JavaScript and Rust. And so today I want to talk with you, how you can supercharge your JavaScript and Node.js experience using the Rust programming language. So let's dive in.

We all know that Node.js is great. It has a great ecosystem of packages. I think it's the biggest ecosystem of packages among all programming languages. It has a very nice development experience. You can pretty much write and rest the server in a few lines of code. TypeScript is making the experience even greater. So you can get type checking that's not statically typed language, but still the type checking, which is nice.

But Node.js is also slow sometimes, especially if you are doing like CPU tasks. Let's say, the generation, maybe image processing. I've seen people do very creative solutions to these problems like outsourcing CPU bound task to message due to another process, which can work on that. And some people do Lambda servers that you can call on demand if you have some heavy computation. But there is also other solution. And the solution is actually writing native modules in either C or C++ or Rust. Now you probably ask why Rust, or what is Rust, why not just use C or C++. So let's try to answer this question first.

And as you probably know, C and C++, they're pretty old, they already showed their age. They're still in development. I think C++ has the 21st version now. I'm not pretty sure, I don't follow it pretty much, but nevertheless, they're old, they're a bit messy. They lack modern tooling. There is no decent dependency manager and they have a relatively poor standard library. So most of the time when you do need heavy containers or iterators, you have to put a library that's called Boost. Many things from Boost get into the C++ specification, but it still lacks a lot of things. The biggest downside, in my opinion, is that they are not memory-safe. So you probably saw this message that we all hate, core dumps, implementation fault, because somewhere you forgot to stop your for loop and you iterated too much on your array or you access the memory that is no longer owned by the application. This makes development in C and C++ very hard. Rust on the other hand, is a strongly typed and compiled language like C and C++.

2. Integrating Rust and JavaScript with NEON

Short description:

Rust has a rich standard library and powerful tooling, including Cargo. It guarantees memory safety and checks for errors at compile time. To integrate Rust and JavaScript, we can use NEON, an open-source library for embedding Rust in Node.js. NEON allows us to write glue code to convert JavaScript types into Rust types. We can export Rust functions back to JavaScript using NEON. To build NEON projects, we use the Cargo-cprtfacts tool. By requiring the native library in Node.js, we can access the exported functions.

It has a rich standard library, so you get smart call, iterators, everything is built into the language itself. You don't need any third-party packages to add support for such things. It has a model tooling, so you have Cargo, which is an NPM equivalent, and you can run tasks with it, you can install packages with Cargo.

The biggest pro in my opinion is that Rust is memory safe. The way they achieve memory safety is very interesting, I'm not going to dive deep into it, you can read about it if you're interested. The notion with Rust is that if it compiles, it will run, so there will be no memory errors. The memory is actually checked on compile time, it's a big pro in my opinion, compared to C or C++. You still can write on SafeRust, it is possible, but by default, all Rust that you write is SafeRust and checked in compilation time.

Well, great to know, but you and I, we all write JavaScript, so how can we integrate between the two? So enter NEON. NEON is a library in the 2Chain for embedding Rust in Node.js. It's an open-source project, and it's a very cool project, I suggest you check it. And let's take a look at the Fibonacci function that we write in Rust and export it into JavaScript world. So, below is the code. Don't worry, I'll have links to my Github later in the presentation, so you can find executable examples. But for now, let's focus on this example, and let's break it into a few buckets so it will be easier to analyze.

On lines 1-4, we have the import and require statement equivalents from Node.js. So we bring some stuff from the NEON library. Line 6-12 is the actual Fibonacci function. Nothing fancy in here, it's a recursive function that goes and searches for the required Fibonacci number. Now, lines 14-18 are what I call a glue layer between the JavaScript world and the Rust world, and since the two languages are different and architectured in a different way, we need a way to convert JavaScript types into Rust types. So you always have to write some glue layer in NEON that will convert your JavaScript into Rust calls, and this is what we are doing on those five lines. We are converting the JavaScript call into a Rust call, and we actually call a Fibonacci function, return the result back to JavaScript, and as with every executable, we need to have a main function. In case of NEON, the main function functions is an export statement and so you can export functions from Rust back to JavaScript world. In that case, we export the Fibonacci API function as Fibonacci-rhs, so in JavaScript, we can access it as Fibonacci-rhs. In order to build this, there is another tool that the NEON team maintains. It's called Cargo-cprtfacts. It copies the artifact that Cargobuild produces, and what it does behind the line, actually generating a dynamic library, so with DLL or SOA equivalent, if you're on Windows or Unix, but it has all the wrappings of NEON and Node.js APIs, because Node.js does not support foreign function interface. Actually, JavaScript does not support foreign function interface, but Node.js supports, so this is why we can write native libraries for Node.js. In order to call the native library, we require it like a regular Node.js module. We can see on line 1, the index node that we've generated previously.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
Utilising Rust from Vue with WebAssembly
Vue.js London Live 2021Vue.js London Live 2021
8 min
Utilising Rust from Vue with WebAssembly
Top Content
Rust is a new language for writing high-performance code, that can be compiled to WebAssembly, and run within the browser. In this talk you will be taken through how you can integrate Rust, within a Vue application, in a way that's painless and easy. With examples on how to interact with Rust from JavaScript, and some of the gotchas to be aware of.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.
Debugging JS
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
As developers, we spend much of our time debugging apps - often code we didn't even write. Sadly, few developers have ever been taught how to approach debugging - it's something most of us learn through painful experience.  The good news is you _can_ learn how to debug effectively, and there's several key techniques and tools you can use for debugging JS and React apps.
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
Do you know what’s really going on in your node_modules folder? Software supply chain attacks have exploded over the past 12 months and they’re only accelerating in 2022 and beyond. We’ll dive into examples of recent supply chain attacks and what concrete steps you can take to protect your team from this emerging threat.
You can check the slides for Feross' talk here.

Workshops on related topic

Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
Node.js Masterclass
Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Top Content
Workshop
Matteo Collina
Matteo Collina
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.
Build a powerful DataGrid in few hours with Ag Grid
React Summit US 2023React Summit US 2023
96 min
Build a powerful DataGrid in few hours with Ag Grid
WorkshopFree
Mike Ryan
Mike Ryan
Does your React app need to efficiently display lots (and lots) of data in a grid? Do your users want to be able to search, sort, filter, and edit data? AG Grid is the best JavaScript grid in the world and is packed with features, highly performant, and extensible. In this workshop, you’ll learn how to get started with AG Grid, how we can enable sorting and filtering of data in the grid, cell rendering, and more. You will walk away from this free 3-hour workshop equipped with the knowledge for implementing AG Grid into your React application.
We all know that rolling our own grid solution is not easy, and let's be honest, is not something that we should be working on. We are focused on building a product and driving forward innovation. In this workshop, you'll see just how easy it is to get started with AG Grid.
Prerequisites: Basic React and JavaScript
Workshop level: Beginner
Build and Deploy a Backend With Fastify & Platformatic
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Matteo Collina
Matteo Collina
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher