25 releases (4 stable)

new 1.0.3 Nov 20, 2024
1.0.1 Oct 27, 2024
1.0.0-beta.5 Jul 31, 2024
0.1.3 Mar 11, 2024
0.0.3 Nov 28, 2023

#51 in FFI

Download history 940/week @ 2024-07-31 838/week @ 2024-08-07 1599/week @ 2024-08-14 1019/week @ 2024-08-21 1103/week @ 2024-08-28 1198/week @ 2024-09-04 979/week @ 2024-09-11 579/week @ 2024-09-18 910/week @ 2024-09-25 960/week @ 2024-10-02 1090/week @ 2024-10-09 1242/week @ 2024-10-16 1133/week @ 2024-10-23 1054/week @ 2024-10-30 917/week @ 2024-11-06 517/week @ 2024-11-13

3,784 downloads per month
Used in 4 crates (3 directly)

MIT license

505KB
15K SLoC

ohos-rs

Crates.io Version Platform License: MIT

Please visit the official website: https://ohos.rs

Discussion

Feel free to join our WeChat group!


lib.rs:

High level Node.js N-API binding

napi-rs provides minimal overhead to write N-API modules in Rust.

Feature flags

napi1 ~ napi8

Because Node.js N-API has versions. So there are feature flags to choose what version of N-API you want to build for. For example, if you want build a library which can be used by node@10.17.0, you should choose the napi5 or lower.

The details of N-API versions and support matrix: Node-API version matrix

tokio_rt

With tokio_rt feature, napi-rs provides a tokio runtime in an additional thread. And you can easily run tokio future in it and return promise.

use futures::prelude::*;
use napi_ohos::{CallContext, Error, JsObject, JsString, Result, Status};
use tokio;

#[napi]
pub async fn tokio_readfile(js_filepath: String) -> Result<JsBuffer> {
    ctx.env.execute_tokio_future(
        tokio::fs::read(js_filepath)
          .map(|v| v.map_err(|e| Error::new(Status::Unknown, format!("failed to read file, {}", e)))),
        |&mut env, data| env.create_buffer_with_data(data),
    )
}

latin1

Decode latin1 string from JavaScript using encoding_rs.

With this feature, you can use JsString.as_latin1_string function

serde-json

Enable Serialize/Deserialize data cross JavaScript Object and Rust struct.

#[derive(Serialize, Debug, Deserialize)]
struct AnObject {
    a: u32,
    b: Vec<f64>,
    c: String,
}

#[napi]
fn deserialize_from_js(arg0: JsUnknown) -> Result<JsUndefined> {
    let de_serialized: AnObject = ctx.env.from_js_value(arg0)?;
    ...
}

#[napi]
fn serialize(env: Env) -> Result<JsUnknown> {
    let value = AnyObject { a: 1, b: vec![0.1, 2.22], c: "hello" };
    env.to_js_value(&value)
}

Dependencies

~0.3–10MB
~119K SLoC