How to Call Rust from JavaScript/Node.js (Neon, napi-rs)

Use the napi-rs crate to define exported functions with #[napi] attributes, build them with 'napi build', and import the resulting binary in Node.js.

Use napi-rs to compile Rust code into a Node.js-compatible binary that JavaScript can import directly.

  1. Initialize a new Rust project with the napi binary template: cargo init --name my-rust-lib --bin && cargo add napi --features=serde.
  2. Create src/lib.rs and define an exported function using the #[napi] attribute: #[napi] pub fn add(a: i32, b: i32) -> i32 { a + b }.
  3. Build the native module for your current platform: napi build --platform --release.
  4. Import and call the function in your JavaScript file: const { add } = require('./index.node'); console.log(add(1, 2));.