node-bindgen 0.1.0

easy way to write nodejs module using rust
Documentation

node-bindgen

Write native nodejs module using idiomatic rust easy way.

Example


use node_bindgen::derive::node_bindgen;

/// generate nodejs sum function
#[node_bindgen]
fn sum(first: i32, second: i32) -> i32 {        
    first + second
}

Then can import as nodejs module!

let addon = require('./dylib');

addon.sum(1,2)
3

N-API

This crates uses Node N-API.

Build

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.

More examples

Callback

Javascript callback can be easily called:

#[node_bindgen]
fn hello<F: Fn(String)>(first: f64, second: F) {

    let msg = format!("argument is: {}", first);

    second(msg);
}

from node:

let addon = require('./dylib');

addon.hello(2,function(msg){
  assert.equal(msg,"argument is: 2");
  console.log(msg);  // print out argument is 2
});

Async functions

Async rust function will return as promise.


use std::time::Duration;
use flv_future_core::sleep;
use node_bindgen::derive::node_bindgen;


#[node_bindgen]
async fn hello(arg: f64) -> f64 {
    println!("sleeping");
    sleep(Duration::from_secs(1)).await;
    println!("woke and adding 10.0");
    arg + 10.0
}
let addon = require('./dylib');

addon.hello(5).then((val) => {
  console.log("future value is{}",val);
});

JavaScript class

JavaScript class can be implemented easily.


struct MyClass {
    val: f64,
}


#[node_bindgen]
impl MyClass {

    #[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
    }
}
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);