rust-nodejs
Embedding Node.js in Rust.
- Provide a global thread-safe Node.js channel.
- Interact with the Node.js runtime via Neon API.
- Link with prebuilt Node.js binaries to save compile time.
- Native modules are supported.
Usage
- Add rust-nodejs to your cargo project:
toml
[dependencies]
nodejs = "0.2.0"
let channel = nodejs::channel()
to get the global Node.js channel.
- Call
channel.send
to run tasks in the Node.js event queue
- Inside the task, use
nodejs::neon
for interoperability between Node.js and Rust. Neon documentation
- On macOS or Linux, add
-Clink-args=-rdynamic
to rustflags
when building your Rust application.
Example
```rust
use nodejs::neon::{context::Context, reflect::eval, types::JsNumber};
fn main() {
let (tx, rx) = std::sync::mpsc::syncchannel::(0);
let channel = nodejs::channel();
channel.send(move |mut cx| {
let script = cx.string("require('os').freemem()");
let freemem = eval(&mut cx, script)?;
let freemem = freemem.downcastorthrow::(&mut cx)?;
tx.send(freemem.value(&mut cx) as i64).unwrap();
Ok(())
});
let freemem = rx.recv().unwrap();
println!("Free system memory: {}", free_mem);
}
```