# How do I call Rust from Node.js with napi-rs?
Source: https://ruststudio.org/community/t/272/how-do-i-call-rust-from-node-js-with-napi-rs
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, napi 3.16.3, napi-derive 3.7.2, napi-build 2.7.0, Node.js v22.19.0, Windows 11 (built with cargo; the napi command line tool was not run)
Category: Help and questions | Kind: FAQ | Tags: javascript, napi, ffi | Views: 0

## Short answer
Build a cdylib crate with the napi and napi-derive crates, mark functions with the napi attribute, and add a build script that calls napi_build::setup. The compiled library, renamed to a .node file, loads with require. Rust errors become thrown JavaScript exceptions, and Rust names become camelCase.

## Answer
## 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`).

```toml title=Cargo.toml
[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"
```

```rust title=build.rs
fn main() {
    napi_build::setup();
}
```

```rust title=src/lib.rs
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.

```javascript title=use.js
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); }
```

```text
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
1. 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.
2. Annotate each exported function with `#[napi]`. Use plain types: integers, floats, `String`, `Vec<T>`, `Option<T>`, `bool`. Use `napi::Result<T>` for functions that can fail.
3. 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.
4. Build with `--release`, rename the library to `.node`, and `require` it. For distribution, build once per operating system and processor, and publish the files in a package.
5. 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
