Using Rust from within Node.js. Or extending Node.js via N-API using NAPI-RS.

applied.math.coding
6 min readMar 11, 2022

Several ways exists to run Rust code from within Node.js. In this post we will look at a relatively smart one, that is, NAPI-RS.

First of all, for what reason makes it sense to have Node.js calling Rust functions?

This question has many answers and we cannot possible cover all the scenarios. Let me give an example of usage:

Node.js is one of the best supporting back-end technologies for various web-applications. It is relatively small, can handle many requests and fits fantastically into micro-service architectures. Moreover, front-end and business-logic can be implemented very quickly since the combination of JavaScript and TypeScript leaves you with one of the best type system that almost never is in your way.

However, when it comes to CPU intensive tasks, Node.js is slow compared to languages like C++ or Rust. Furthermore, Node.js’s support for multi-threading is but there, but by far not so sophisticated and optimized as the one of Rust. At the same time, Rust as well has a relatively small memory footprint.

All this together can lead to the desire to use Node.js to control the logic that puts together the endpoints towards the requests of persisting data, but to delegate all CPU intensive tasks that might…

--

--

applied.math.coding

I am a Software Developer - Java, Rust, SQL, TypeScript - with strong interest doing research in pure and applied Mathematics.