node-bindgen

Easy way to write Node.js module using Rust

README

node-bindgen


Easy way to write native Node.js module using idiomatic Rust

Features


- __Easy:__ Just write idiomatic Rust code, node-bindgen take care of generating Node.js FFI wrapper codes.
- __Safe:__ Node.js arguments are checked automatically based on Rust types.
- __Async:__ Support Async Rust.  Async codes are translated into Node.js promises.
- __Class:__ Rust struct can be accessed using Node.js classes.
- __Stream:__ Implement Node.js stream using Rust
- __N-API:__ Use Node.js N-API, which means you don't have to recompile your module.

Compatibility with Node.js version


This project uses the v7 of Node N-API.  Please see following compatibility matrix.

Following OS are supported:
Linux
MacOs
Windows



Why node-bindgen?


Writing native node-js requires lots of boilerplate code.  Node-bindgen generates external "C" glue code from rust code, including native module registration.  node-bindgen make it writing node-js module easy and fun.


Getting started


CLI Installation


Install nj-cli command line, which will be used to generate the native library.

  1. ```
  2. cargo install nj-cli
  3. ```

This is a one time step.

Configuring Cargo.toml


Add two dependencies to your projects' Cargo.toml.

Add node-bindgen as a regular dependency (as below):
  1. ```
  2. [dependencies]
  3. node-bindgen = { version = "5.1" }
  4. ```

Then add node-bindgen's procedure macro to your build-dependencies as below:
  1. ```
  2. [build-dependencies]
  3. node-bindgen = { version = "5.1", features = ["build"] }
  4. ```

Then update crate type to cdylib to generate node.js compatible native module:
  1. ```
  2. [lib]
  3. crate-type = ["cdylib"]
  4. ```

Finally, add build.rs at the top of the project with following content:

  1. ```
  2. fn main() {
  3.     node_bindgen::build::configure();
  4. }
  5. ```


Example


Here is a function that adds two numbers.  Note that you don't need to worry about JS conversion.


  1. ```rust

  2. use node_bindgen::derive::node_bindgen;

  3. /// add two integer
  4. #[node_bindgen]
  5. fn sum(first: i32, second: i32) -> i32 {
  6.     first + second
  7. }

  8. ```

Building native library


To build node.js library, using nj-cli to build:

  1. ```
  2. nj-cli build
  3. ```

This will generate Node.js module in "./dist" folder.

To build a release version:
  1. ```
  2. nj-cli build --release
  3. ```

Watching ./src for Changes


While developing your native module, you may want to watch for file changes and run a command when a change occurs, for example cargo check or cargo build.

For this, we can use nj-cli watch.

`nj-cli watch` installs [if it does not exist] and passes arguments to [`cargo watch`](https://crates.io/crates/cargo-watch). By default, `nj-cli watch` will run `cargo check` against your `./src` files.

To see all available methods for nj-cli watch, run the following command:

nj-cli watch -- --help


Using in Node.js


Then in the Node.js, rust function can be invoked as normal node.js function:

  1. ```js
  2. $ node
  3. Welcome to Node.js v14.0.0.
  4. Type ".help" for more information.
  5. > let addon = require('./dist');
  6. undefined
  7. > addon.sum(2,3)
  8. 5
  9. >
  10. ```


Features


Function name or method can be renamed instead of default mapping


  1. ```rust
  2. #[node_bindgen(name="multiply")]
  3. fn mul(first: i32,second: i32) -> i32 {
  4.     first * second
  5. }
  6. ```

Rust function mul is re-mapped as multiply

Optional argument


Argument can be skipped if it is marked as optional
  1. ```rust
  2. #[node_bindgen]
  3. fn sum(first: i32, second: Option<i32>) -> i32 {
  4.     first + second.unwrap_or(0)
  5. }
  6. ```
Then sum can be invoked as
  1. ```sum(10)``` or ```sum(10,20)```


  2. ##  Callback

  3. JS callback are mapped as Rust closure.

  4. ```rust
#[node_bindgen]
fn hello(first: f64, second: F) {

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

    second(msg);
}
  1. ```

  2. from node:

  3. ```js
let addon = require('./dist');

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

  2. Callback are supported in Async rust as well.

  3. ## Support for Async Rust

  4. Async rust function is mapped to Node.js promise.

  5. ```rust

use std::time::Duration;
use flv_future_aio::time::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
}
  1. ```

  2. ```js
let addon = require('./dist');

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

  1. ```

  2. ## Struct serialization

  3. Structs, including generic structs, can have have the to-JS conversion boilerplate autogenerated.
  4. Just apply the `node_bindgen` macro to your struct:

  5. ```rust
#[node_bindgen]
struct MyJson {
    some_name: String,
    a_number: i64
}

#[node_bindgen]
fn my_json() -> MyJson {
    MyJson {
        some_name: "John".to_owned(),
        a_number: 1337
    }
}
  1. ```

  2. ```js
let addon = require('./dist');
assert.deepStrictEqual(addon.my_json(), {
    someName: "John",
    aNumber: 1337
});
  1. ```

  2. Note that the fields must implement
  3. `node_bindgen::core::TryIntoJs` themselves.
  4. Any references must also implement `Clone`.
  5. Field names will be converted to camelCase.

  6. ## Enums

  7. Enums will also have their JS representation autogenerated with the help of `node_bindgen`:

  8. ```rust
#[node_bindgen]
enum ErrorType {
    WithMessage(String, usize),
    WithFields {
        val: usize
    },
    UnitErrorType
}

#[node_bindgen]
fn with_message() -> ErrorType {
    ErrorType::WithMessage("test".to_owned(), 321)
}

#[node_bindgen]
fn with_fields() -> ErrorType {
    ErrorType::WithFields {
        val: 123
    }
}

#[node_bindgen]
fn with_unit() -> ErrorType {
    ErrorType::UnitErrorType
}
  1. ```

  2. ```js
assert.deepStrictEqual(addon.withMessage(), {
    withMessage: ["test", 321n]
});
assert.deepStrictEqual(addon.withFields(), {
    withFields: {
        val: 123n
    }
});
assert.deepStrictEqual(addon.withUnit(), "UnitErrorType")
  1. ```

  2. Tuple variants will be converted into lists, struct variants converted to objects, and unit variants converted into strings matching the variant's name in PascalCase.
  3. Generics and references are supported, with the same caveats as for structs.

  4. ## JavaScript class

  5. JavaScript class is supported.

  6. ```rust

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
    }
}
  1. ```

  2. ```js
let addon = require('./dist');
const assert = require('assert');

let obj = new addon.MyObject(10);
assert.equal(obj.value,10,"verify value works");
assert.equal(obj.plusOne(),11);
  1. ```

  2. There are more features in the examples folder.

  3. ## Windows + Electron Support
  4. When using node-bindgen with electron on Windows, `nj-build` must
  5. compile a C++ file, `win_delay_load_hook.cc`, and therefore it is required that the development
  6. environment has a valid C/C++ compiler.

  7. > If your machine does not have a valid C/C++ compiler, install [Microsoft VSCode](https://code.visualstudio.com/docs/cpp/config-mingw).

  8. In the future, this file will be re-written in Rust, removing this dependency.

  9. Just make sure that you are compiling the rust module using
  10. ```
$ npx electron-build-env nj-cli build --release
  1. ```

  2. otherwise you will get dreaded  `A dynamic link library (DLL) initialization routine failed` when importing the rust module in electron

  3. ## Contributing

  4. If you'd like to contribute to the project, please read our [Contributing guide](CONTRIBUTING.md).

  5. ## License

  6. This project is licensed under the [Apache license](LICENSE-APACHE).