🚀 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!

This talk has been presented at JSNation 2022, check out the latest edition of this JavaScript Conference.

FAQ

Dmitry Kudravtsev is a senior software engineer passionate about JavaScript and Rust.

Developers might choose Rust over C or C++ because Rust is memory-safe, has a rich standard library, modern tooling like Cargo, and avoids many common pitfalls of C and C++ regarding memory management.

NEON is a library that allows embedding Rust in Node.js, enabling developers to write native modules in Rust and use them in JavaScript.

Native Rust modules are generally faster than WebAssembly because they bypass the virtual machine layer, but WebAssembly is still very fast and offers good performance improvements over JavaScript.

WebAssembly offers better portability and ergonomics, allowing code to run across different platforms and browsers without needing recompilation.

No, WebAssembly cannot access system-level features like file systems and networking directly. This is a limitation compared to native Rust modules.

AssemblyScript is a specialized language similar to TypeScript that compiles to WebAssembly, allowing developers to write WebAssembly code more easily.

Native Rust modules should be used to extend Node.js with high-performance code, while WebAssembly is better for replacing non-performant JavaScript code and ensuring cross-platform compatibility.

Native modules are machine-dependent and need to be recompiled for different operating systems and architectures, unlike WebAssembly, which can run on any platform with a WebAssembly virtual machine.

Rust can improve the performance of JavaScript and Node.js by allowing the creation of native modules, which are faster for CPU-intensive tasks like image processing or data generation.

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
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
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
In this Talk, the speaker demonstrates how to use Rust with WebAssembly in a Vue.js project. They explain that WebAssembly is a binary format that allows for high-performance code and less memory usage in the browser. The speaker shows how to build a Rust example using the WasmPack tool and integrate it into a Vue template. They also demonstrate how to call Rust code from a Vue component and deploy the resulting package to npm for easy sharing and consumption.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
Debugging JS
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
Watch video: Debugging JS
Debugging JavaScript is a crucial skill that is often overlooked in the industry. It is important to understand the problem, reproduce the issue, and identify the root cause. Having a variety of debugging tools and techniques, such as console methods and graphical debuggers, is beneficial. Replay is a time-traveling debugger for JavaScript that allows users to record and inspect bugs. It works with Redux, plain React, and even minified code with the help of source maps.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
WebAssembly enables optimizing JavaScript performance for different environments by deploying the JavaScript engine as a portable WebAssembly module. By making JavaScript on WebAssembly fast, instances can be created for each request, reducing latency and security risks. Initialization and runtime phases can be improved with tools like Wiser and snapshotting, resulting in faster startup times. Optimizing JavaScript performance in WebAssembly can be achieved through techniques like ahead-of-time compilation and inline caching. WebAssembly usage is growing outside the web, offering benefits like isolation and portability. Build sizes and snapshotting in WebAssembly depend on the application, and more information can be found on the Mozilla Hacks website and Bike Reliance site.
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
The talk discusses the importance of supply chain security in the open source ecosystem, highlighting the risks of relying on open source code without proper code review. It explores the trend of supply chain attacks and the need for a new approach to detect and block malicious dependencies. The talk also introduces Socket, a tool that assesses the security of packages and provides automation and analysis to protect against malware and supply chain attacks. It emphasizes the need to prioritize security in software development and offers insights into potential solutions such as realms and Deno's command line flags.

Workshops on related topic

Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Top Content
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
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 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.