napi-rs Docs

Registering module

Registering module

Module could be registered by module_exports macro:

lib.rs
#[macro_use]
extern crate napi_derive;
use napi::*;
#[module_exports]
fn init(mut exports: JsObject) -> Result<()> {
exports.create_named_method("hello", hello)?;
Ok(())
}
#[js_function]
fn hello(ctx: CallContext) -> Result<JsString> {
todo!()
}

There can also be a second argument Env:

lib.rs
#[macro_use]
extern crate napi_derive;
use napi::*;
#[module_exports]
fn init(mut exports: JsObject, env: Env) -> Result<()> {
exports.create_named_method("hello", hello)?;
exports.set_named_property("MAX_SAFE_SIZE", env.create_uint32(1000)?)?;
Ok(())
}
#[js_function]
fn hello(ctx: CallContext) -> Result<JsString> {
todo!()
}
const native = require('./index.node')
console.log(native.MAX_SAFE_SIZE) // 1000
Edit this page on GitHub