Node Bridge

Simple rust script to achieve a bridge between node.js and rust. Use with the npm package rust-bridge. Only 1 bridge can be initialized per rust program. But node.js can have many bridges.

Installation

Add the following line to your Cargo.toml under [dependencies]

toml node_bridge = "1.0.0"

Node.js installation: bash $ npm install rustlang-bridge

Usage/Examples

```rust use node_bridge::NodeBridge;

[tokio::main]

async fn main() { let bridge = NodeBridge::new(); bridge.register("addition", add, None); bridge.registerasync("findlonger", findlonger, Some("Variable to pass to the function")); asserteq!(bridge.receive("channela").await.unwrap(), "Sent this from node!"); bridge.send("channelfoo", "bar").ok(); bridge.waituntilcloses().await; }

fn add(params: Vec, _: Option<()>) -> i32 { params[0] + params[1] }

async fn findlonger(params: Vec, passdata: Option<&str>) -> String { asserteq!(passdata, Some("Variable to pass to the function")); if params[0].len() > params[1].len() { return params[0].tostring(); } params[1].tostring() } ```

Handling in node.js:

```javascript import RustBridge from "rustlang-bridge";

const bridge = new RustBridge("/path/to/rustexecutable"); await new Promise(resolve => setTimeout(resolve, 500)); // wait for the functions to initialize console.log(await bridge.addition(10, 20)); // "30" console.log(await bridge.findlonger("foo", "longerfoo")); // "longerfoo" bridge.on("channelfoo", data => { console.log(data); // "bar" }); bridge.send("channela", "Sent this from node!"); ```

Contributing

Contributions are always welcome!