mirror of
https://github.com/napi-rs/napi-rs.git
synced 2025-12-08 19:56:07 +00:00
docs: update example in README (#2660)
This commit is contained in:
parent
f8fab45de7
commit
9cccc46790
@ -57,13 +57,12 @@ One nice feature is that this crate allows you to build add-ons purely with the
|
||||
### Define JavaScript functions
|
||||
|
||||
```rust
|
||||
/// import the preludes
|
||||
use napi::bindgen_prelude::*;
|
||||
use napi_derive::napi;
|
||||
|
||||
/// module registration is done by the runtime, no need to explicitly do it now.
|
||||
#[napi]
|
||||
fn fibonacci(n: u32) -> u32 {
|
||||
pub fn fibonacci(n: u32) -> u32 {
|
||||
match n {
|
||||
1 | 2 => 1,
|
||||
_ => fibonacci(n - 1) + fibonacci(n - 2),
|
||||
@ -73,30 +72,31 @@ fn fibonacci(n: u32) -> u32 {
|
||||
/// use `Fn`, `FnMut` or `FnOnce` traits to defined JavaScript callbacks
|
||||
/// the return type of callbacks can only be `Result`.
|
||||
#[napi]
|
||||
fn get_cwd<T: Fn(String) -> Result<()>>(callback: T) {
|
||||
callback(env::current_dir().unwrap().to_string_lossy().to_string()).unwrap();
|
||||
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]
|
||||
fn test_callback<T>(callback: T)
|
||||
where T: Fn(String) -> Result<()>
|
||||
{}
|
||||
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]
|
||||
async fn read_file_async(path: String) -> Result<Buffer> {
|
||||
tokio::fs::read(path)
|
||||
.map(|r| match r {
|
||||
Ok(content) => Ok(content.into()),
|
||||
Err(e) => Err(Error::new(
|
||||
Status::GenericFailure,
|
||||
format!("failed to read file, {}", e),
|
||||
)),
|
||||
})
|
||||
.await
|
||||
pub async fn read_file_async(path: String) -> Result<Buffer> {
|
||||
Ok(tokio::fs::read(path).await?.into())
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user