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