This project is forked from napi-rs, many thank to @Brooooooklyn.
1.88.0
You can use ohrs to start a new project.
use napi_ohos::bindgen_prelude::*;
use napi_derive_ohos::napi;
/// module registration is done by the runtime, no need to explicitly do it now.
#[napi]
pub fn fibonacci(n: u32) -> u32 {
match n {
1 | 2 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
/// use `Fn`, `FnMut` or `FnOnce` traits to defined JavaScript callbacks
/// the return type of callbacks can only be `Result`.
#[napi]
pub fn get_cwd<T: Fn(String) -> Result<()>>(callback: T) {
callback(
std::env::current_dir()
.unwrap()
.to_string_lossy()
.to_string(),
)
.unwrap();
}
/// or, define the callback signature in where clause
#[napi]
pub fn test_callback<T>(callback: T) -> Result<()>
where
T: Fn(String) -> Result<()>,
{
callback(std::env::current_dir()?.to_string_lossy().to_string())
}
/// async fn, require `async` feature enabled.
/// [dependencies]
/// napi = {version="2", features=["async"]}
#[napi]
pub async fn read_file_async(path: String) -> Result<Buffer> {
Ok(tokio::fs::read(path).await?.into())
}Before build, we must setup some environments. You can follow the document to setup them.
Then you can use ohrs to build it directly.
ohrs build
# build single arch
ohrs build --arch aarchFinally you can copy the dist folder into your OpenHarmony/HarmonyNext project and use it.
We use tokio as the default asynchronous runtime. But for some simple scenarios, we don't need so complete runtime, and you can try ohos-ffrt.