Easy way to write native Node.js module using idiomatic rust.
```rust
use nodebindgen::derive::nodebindgen;
/// generate nodejs sum function
fn sum(first: i32, second: i32) -> i32 {
first + second
}
```
Import as Node.js module!
```js let addon = require('./dylib');
addon.sum(1,2) 3 ```
This crates utilizes Node N-API.
Use nj-cli to generate native module. First install:
cargo install nj-cli
Build command to generate module directory.
nj-cli build
This will generates ".dylib" folder.
Use rust closure to invoke JS callback
```rust
fn hello }
``` from node: ```js
let addon = require('./dylib'); addon.hello(2,function(msg){
assert.equal(msg,"argument is: 2");
console.log(msg); // print out argument is 2
}); ``` Async rust function will return as promise. ```rust use std::time::Duration;
use flvfuturecore::sleep;
use nodebindgen::derive::nodebindgen; async fn hello(arg: f64) -> f64 {
println!("sleeping");
sleep(Duration::from_secs(1)).await;
println!("woke and adding 10.0");
arg + 10.0
}
``` ```js
let addon = require('./dylib'); addon.hello(5).then((val) => {
console.log("future value is{}",val);
}); ``` JavaScript class can be implemented easily. ```rust struct MyClass {
val: f64,
} impl MyClass { }
``` ```js
let addon = require('./dylib');
const assert = require('assert'); let obj = new addon.MyObject(10);
assert.equal(obj.value,10,"verify value works");
assert.equal(obj.plusOne(),11);
```let msg = format!("argument is: {}", first);
second(msg);
Async functions
[node_bindgen]
JavaScript class
[node_bindgen]
#[node_bindgen(constructor)]
fn new(val: f64) -> Self {
Self { val }
}
#[node_bindgen]
fn plus_one(&self) -> f64 {
self.val + 1.0
}
#[node_bindgen(getter)]
fn value(&self) -> f64 {
self.val
}