Answer#
A Node.js native addon is a shared library that exports one initialisation function, which Node calls when you require it. napi-rs is a set of Rust crates that write that glue: the #[napi] attribute turns a Rust function into a JavaScript function and converts arguments and results. The addon uses Node-API, the stable binary interface of Node.js, so one build works across Node.js versions that support the Node-API level you ask for (here napi4).
[package]
name = "napidemo"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
napi = { version = "3", default-features = false, features = ["napi4"] }
napi-derive = "3"
[build-dependencies]
napi-build = "2"fn main() {
napi_build::setup();
}use napi_derive::napi;
/// Number of words in `text`.
#[napi]
pub fn word_count(text: String) -> u32 {
text.split_whitespace().count() as u32
}
/// Mean of the numbers; returns an error to JavaScript (a thrown exception) when the list is empty.
#[napi]
pub fn mean(values: Vec<f64>) -> napi::Result<f64> {
if values.is_empty() {
return Err(napi::Error::from_reason("mean of an empty list"));
}
Ok(values.iter().sum::<f64>() / values.len() as f64)
}cargo build --release produced napidemo.dll here. Copy it to napidemo.node (on Linux the file is libnapidemo.so, on macOS libnapidemo.dylib; the extension .node is what require looks for). The napi command line tool from the napi-rs project automates this and the packaging for several platforms; it was not run for this thread.
const m = require("./napidemo.node");
console.log(m.wordCount("one two three"));
console.log(m.mean([1, 2, 6]));
try { m.mean([]); } catch (e) { console.log("caught:", e.message); }
try { m.wordCount(42); } catch (e) { console.log("caught:", e.code, e.message); }3
3
caught: mean of an empty list
caught: StringExpected Failed to convert JavaScript value `Number 42 ` into rust type `String`Notice that the Rust function word_count is called wordCount in JavaScript: napi-rs converts names to camelCase. A Result::Err is thrown as a JavaScript Error, and a wrong argument type (a number where a string is expected) is also thrown, with the code StringExpected, before your Rust code runs.
How to do it#
- Create the crate as a library with
crate-type = ["cdylib"]and the three dependencies above. Pin the versions you tested; the napi-rs crates have changed their API between major versions. - Annotate each exported function with
#[napi]. Use plain types: integers, floats,String,Vec<T>,Option<T>,bool. Usenapi::Result<T>for functions that can fail. - For work that takes long, use an asynchronous function or a task that runs on a thread pool, so the JavaScript event loop stays free. A synchronous function like those above blocks the event loop while it runs.
- Build with
--release, rename the library to.node, andrequireit. For distribution, build once per operating system and processor, and publish the files in a package. - Test from JavaScript with the same inputs as the old JavaScript function (see the thread on golden files).
Common mistakes#
- Moving a function to Rust that is called a million times with small arguments. Each call crosses the boundary and converts values. Port a function that does a lot of work per call.
- Doing slow work in a synchronous
#[napi]function. It freezes the server's event loop for the duration. - Mixing addon and Node.js architectures (a 64-bit addon cannot load into a 32-bit Node.js).
Related questions#
Should I use WebAssembly instead of an addon?#
WebAssembly runs in browsers and in Node.js without per-platform builds, but has its own limits on system access and call overhead. An addon can use the whole operating system. This thread only built and ran the addon route.
Can the addon call back into JavaScript?#
Yes. napi-rs supports calling JavaScript functions from Rust (thread-safe functions for calls from other threads); it was not run here.
Sources#
- napi-rs documentation: https://napi.rs/
- Node.js documentation, "Node-API": https://nodejs.org/api/n-api.html