Skip to content

Examples

The napi-rs/napi-rs repository keeps a set of runnable example projects under examples/. They are the same code the CI test suite exercises, so every snippet compiles and runs against the current release.

The example projects

Project What it shows
examples/napi The kitchen sink: one src/*.rs file per feature area, built for native, wasm32-wasip1, and wasm32-wasip1-threads, with browser, workerd, and Electron test targets. Most code snippets on this site are adapted from here.
examples/napi-compat-mode The v2-era low-level compat-mode API (CallContext, JsBuffer, JsFunction, …) organized by Node-API version. Useful when migrating a v2 addon; see the V2 to V3 migration guide.
examples/napi-shared Sharing #[napi] classes and object shapes between Rust crates (consumed by examples/napi).
examples/napi-cargo-test Testing pure Rust logic with plain cargo test — no Node.js — using the noop feature on napi and napi-derive.
examples/binary Building a Rust bin target with napi-raw build instead of a cdylib addon.
examples/custom-async-runtime A complete hand-rolled AsyncRuntime backend — scheduler, blocking pool, lifecycle hooks — with threadless wasm32-wasip1, workerd, and browser targets.
examples/shared-async-runtime The end-to-end consumer of the published napi-async-runtime crate: install it from #[module_init], then use async fn, sleep_until, and spawn_blocking without Tokio.

Inside examples/napi

The main example crate is organized one file per topic. Quick index:

Values & types

Classes

Async & threads

Streams & fetch

  • stream.rs — accepting and returning Web ReadableStreams, including streams of #[napi(object)] structs (see Web Streams).
  • fetch.rs — a fetch built on reqwest, resolving a promise with a Web Response via AsyncBlockBuilder::build_with_map.

WASI, Env & scopes

  • wasm.rs — threadsafe functions and worker patterns that also run on WASI targets (see WebAssembly).
  • env.rs — low-level Env APIs: run_script, module file names, versions.
  • scope.rsHandleScope / EscapableHandleScope for loops that create many short-lived values (see Env).
  • lifetime.rs — borrowed vs. owned values across calls (see Understanding Lifetime).

Modules, functions & errors

Run them locally

The examples live in the napi-rs workspace and build with the in-repo CLI:

sh
git clone https://github.com/napi-rs/napi-rs.git
cd napi-rs
yarn
yarn build      # build the @napi-rs/* packages (CLI, wasm-runtime, ...)
yarn build:test # build the @examples/* packages with the in-repo CLI

cd examples/napi
yarn test       # ava

The WASI and browser variants have their own scripts — see each example's package.json (for example test:wasi in examples/shared-async-runtime, or test-workerd.mjs / browser/runtime.spec.js in examples/custom-async-runtime).

Last updated on
LongYinan