Write native nodejs module using idiomatic rust easy way.
```rust
use nodebindgen::derive::nodebindgen;
/// generate nodejs sum function
fn sum(first: i32, second: i32) -> i32 {
first + second
}
```
Then can import as nodejs module!
```js let addon = require('./dylib');
addon.sum(1,2) 3 ```
This crates uses Node N-API.
To build nodejs module, first install nj-cli.
cargo install nj-cli
To generate nodejs module:
nj-cli build
This will generate 'dylib' in the current directory.
Javascript callback can be easily called:
```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
}