Skip to content

Commit

Permalink
changes
Browse files Browse the repository at this point in the history
  • Loading branch information
fyhhub authored Nov 21, 2023
1 parent 876fe74 commit e99f2a8
Show file tree
Hide file tree
Showing 5 changed files with 176 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/rust-learn/napi-rs/1.导出class.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# 导出Class

```rust
use std::path::{Path, PathBuf};
use napi_derive::napi;
use tokio::{fs};
use futures::prelude::*;
use napi::bindgen_prelude::*;

// 此处可以通过js_name制定类名
#[napi(js_name = "ClassDemoName")]
pub struct ClassDemo {
name: String
}

#[napi]
impl ClassDemo {
// 设置当前的new方法为构造函数
#[napi(constructor)]
pub fn new() -> Self {
ClassDemo {
name: String::from("123")
}
}

// 设置一个工厂方法,必须返回当前的类, 最后会变成一个静态的方法,并且返回当前类的实例
#[napi(factory)]
pub fn with_initial_count(count: u32) -> ClassDemo {
ClassDemo {
name: String::from(count.to_string())
}
}

// 设置一个普通的异步方法
#[napi]
pub async fn read_dir(&self, query: String) -> napi::Result<String> {
let res = fs::read_to_string(PathBuf::from(query)).await?;
Ok(res)
}

// 设置一个普通方法
#[napi]
pub fn return_string(&self) -> napi::Result<String> {
Ok(String::from("value"))
}

// 设置一个getter
#[napi(getter)]
pub fn name(&self) -> &str {
self.name.as_str()
}

// 设置一个setter
#[napi(setter)]
pub fn set_name(&mut self, s: String) {
self.name = s;
}

// 设置方法的可访问性 writable / enumerable / configurable
#[napi(writable = false)]
pub fn get_name(&self) -> &str {
self.name.as_str()
}
}
```

25 changes: 25 additions & 0 deletions src/rust-learn/napi-rs/2.导出异步函数.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# 导出异步函数

```rust
[dependencies]
napi = { version = "2", features = ["async"] }
```

```rust
use futures::prelude::*;
use napi::bindgen_prelude::*;
use tokio::fs;

#[napi]
async fn read_file_async(path: String) -> Result<Buffer> {
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
}
```
23 changes: 23 additions & 0 deletions src/rust-learn/napi-rs/3.在rust中执行js的Promise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 在rust中执行js的Promise
```rust
use napi::bindgen_prelude::*;

#[napi]
pub async fn async_plus_100(p: Promise<u32>) -> Result<u32> {
let v = p.await?;
Ok(v + 100)
}
```

```js
import { asyncPlus100 } from './index.js'

const fx = 20
const result = await asyncPlus100(
new Promise((resolve) => {
setTimeout(() => resolve(fx), 50)
}),
)

console.log(result) // 120
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# 注入this用来获取js运行时设置的属性

## 在类中使用

```js
import { QueryEngine } from './index.js'

const qe = new QueryEngine()
qe.refCount = 3
console.log(qe.getRefCount()) // 3
```

在上面的例子中, QueryEngine 并没有声明和初始化 refCount, 但是js动态设置了,rust要怎么做才能获取到这个属性呢?

```rust
#[napi]
use napi::bindgen_prelude::*;
use napi_derive::napi;

pub struct QueryEngine {}

#[napi]
impl QueryEngine {
#[napi(constructor)]
pub fn new() -> Result<Self> {
Ok(Self {})
}

#[napi]
pub fn get_ref_count(&self, this: This) -> Result<Option<i32>> {
this.get::<i32>("refCount")
}
}
```




## 在函数中使用
```rust
import { Width, plusOne } from './index.js'

const width = new Width(1)
console.log(plusOne(width)) // 2
```
在上面的例子中,plusOne可能有自己的this上下文

```rust
use napi::bindgen_prelude::*;
use napi_derive::napi;

#[napi(constructor)]
pub struct Width {
pub value: i32,
}

#[napi]
pub fn plus_one(this: This<&Width>) -> i32 {
this.value + 1
}
```
1 change: 1 addition & 0 deletions src/rust-learn/napi-rs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# napi-rs

0 comments on commit e99f2a8

Please sign in to comment.