### Access System Information with Rust Crate Source: https://context7.com/neon-bindings/examples/llms.txt Shows how to call native Rust crates from Node.js to access system-level information. This example uses the num_cpus crate to retrieve CPU count and return it as a JavaScript number. ```rust use neon::prelude::*; fn get_num_cpus(mut cx: FunctionContext) -> JsResult { Ok(cx.number(num_cpus::get() as f64)) } #[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("get", get_num_cpus)?; Ok(()) } ``` ```javascript const cpuCount = require('./index.node'); const numCpus = cpuCount.get(); console.log(`System has ${numCpus} CPUs`); // Output: System has 8 CPUs (example) ``` -------------------------------- ### Async HTTP Request with Tokio and Neon (Rust) Source: https://context7.com/neon-bindings/examples/llms.txt Performs an asynchronous HTTP GET request to fetch Node.js release information and returns the release date for a given version. It utilizes Tokio for async operations and Neon for bridging to Node.js. Dependencies include `neon`, `tokio`, `once_cell`, `serde`, and `reqwest`. ```rust use neon::prelude::*; use once_cell::sync::OnceCell; use tokio::runtime::Runtime; use serde::Deserialize; #[derive(Deserialize)] struct NodeRelease { version: String, date: String, } fn runtime<'a, C: Context<'a>>(cx: &mut C) -> NeonResult<&'static Runtime> { static RUNTIME: OnceCell = OnceCell::new(); RUNTIME.get_or_try_init(|| Runtime::new().or_else(|err| cx.throw_error(err.to_string()))) } async fn fetch_node_release(version: &str) -> Result, reqwest::Error> { let version = reqwest::get("https://nodejs.org/dist/index.json") .await?; .json::>() .await?; .into_iter() .find(|release| release.version == version); Ok(version) } fn node_release_date(mut cx: FunctionContext) -> JsResult { let rt = runtime(&mut cx)?; let version = cx.global::("process")?; .get::(&mut cx, "version")?; .value(&mut cx); let channel = cx.channel(); let (deferred, promise) = cx.promise(); rt.spawn(async move { let release = fetch_node_release(&version).await; deferred.settle_with(&channel, move |mut cx| { let release = release.or_else(|err| cx.throw_error(err.to_string()))?; match release { Some(release) => Ok(cx.string(release.date)), None => cx.throw_error(format!("Could not find version: {}", version)), } }); }); Ok(promise) } #[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("nodeReleaseDate", node_release_date)?; Ok(()) } ``` -------------------------------- ### Export String Function in Rust with Neon Source: https://context7.com/neon-bindings/examples/llms.txt Demonstrates the basic pattern of exporting a Rust function that returns a string to JavaScript using Neon. Shows how to create a function with FunctionContext and export it through the module context. ```rust use neon::prelude::*; fn hello(mut cx: FunctionContext) -> JsResult { Ok(cx.string("hello node")) } #[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("hello", hello)?; Ok(()) } ``` ```javascript const addon = require('./index.node'); const greeting = addon.hello(); console.log(greeting); // Output: "hello node" ``` -------------------------------- ### Rust Gzip Compression Stream with Neon Source: https://context7.com/neon-bindings/examples/llms.txt Implements a Rust-based Gzip compression stream using Neon, designed to run on Node.js worker threads. It handles streaming data, manages mutable state across FFI boundaries, and integrates with Node.js streams for efficient data compression. ```rust use std::sync::{Arc, Mutex}; use flate2::{write::GzEncoder, Compression}; use neon::prelude::*; use neon::types::buffer::TypedArray; #[derive(Clone)] struct CompressStream { encoder: Arc>>>, } impl CompressStream { fn new(level: Compression) -> Self { let encoder = GzEncoder::new(Vec::new(), level); Self { encoder: Arc::new(Mutex::new(encoder)), } } fn write(self, data: Vec) -> Result { self.lock()?.write_all(&data)?; Ok(self) } fn finish(self) -> Result { self.lock()?.try_finish()?; Ok(self) } } impl Finalize for CompressStream {} fn compress_new(mut cx: FunctionContext) -> JsResult> { let stream = CompressStream::new(Compression::best()); Ok(cx.boxed(stream)) } fn compress_chunk(mut cx: FunctionContext) -> JsResult { let stream = (**cx.argument::>(0)?).clone(); let chunk = cx.argument::>(2)?.as_slice(&cx).to_vec(); let promise = cx .task(move || stream.write(chunk)) .promise(CompressStream::and_buffer); Ok(promise) } fn compress_finish(mut cx: FunctionContext) -> JsResult { let stream = CompressStream::clone(&*cx.argument::>(0)?); let promise = cx .task(move || stream.finish()) .promise(CompressStream::and_buffer); Ok(promise) } #[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("compressNew", compress_new)?; cx.export_function("compressChunk", compress_chunk)?; cx.export_function("compressFinish", compress_finish)?; Ok(()) } ``` -------------------------------- ### Async SQLite Database with Thread Safety Source: https://context7.com/neon-bindings/examples/llms.txt Implements a complete asynchronous SQLite database wrapper with thread-safe access. Demonstrates using channels for JavaScript-Rust communication, handling promises, and wrapping native types in JsBox. ```rust use neon::{prelude::*, types::Deferred}; use rusqlite::Connection; use std::sync::mpsc; // Create database instance fn js_new(mut cx: FunctionContext) -> JsResult> { let db = Database::new(&mut cx).or_else(|err| cx.throw_error(err.to_string()))?; Ok(cx.boxed(db)) } // Insert record and return ID fn js_insert(mut cx: FunctionContext) -> JsResult { let name = cx.argument::(0)?.value(&mut cx); let db = cx.this::>()?; let (deferred, promise) = cx.promise(); db.send(deferred, move |conn, channel, deferred| { let result = conn .execute("INSERT INTO person (name) VALUES (?)", rusqlite::params![name]) .map(|_| conn.last_insert_rowid()); deferred.settle_with(channel, move |mut cx| { let id = result.or_else(|err| cx.throw_error(err.to_string()))?; Ok(cx.number(id as f64)) }); }) .into_rejection(&mut cx)?; Ok(promise) } #[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("databaseNew", js_new)?; cx.export_function("databaseInsert", js_insert)?; cx.export_function("databaseGetById", js_get_by_id)?; cx.export_function("databaseClose", js_close)?; Ok(()) } ``` ```javascript const Database = require('./index.js'); async function example() { const db = new Database(); try { // Insert a record const id = await db.insert("Marty McFly"); console.log(`Inserted with ID: ${id}`); // Output: Inserted with ID: 1 // Retrieve by ID const name = await db.byId(id); console.log(`Retrieved name: ${name}`); // Output: Retrieved name: Marty McFly // Non-existent record returns undefined const missing = await db.byId(999); console.log(missing); // Output: undefined } finally { db.close(); } } example().catch(console.error); ``` -------------------------------- ### Initialize Compress Stream in Rust Source: https://github.com/neon-bindings/examples/blob/main/examples/gzip-stream/README.md This Rust function creates a new CompressStream instance using Neon bindings, wrapping it in JsBox for JavaScript access. It initializes the stream with best compression settings and returns it as a JavaScript object. The function follows the pattern of binding 'this' in JavaScript class methods. ```rust fn compress_new(mut cx: FunctionContext) -> JsResult> { let stream = CompressStream::new(Compression::best()); Ok(cx.boxed(stream)) } ``` -------------------------------- ### Insert and query data in SQLite using JavaScript Source: https://github.com/neon-bindings/examples/blob/main/examples/async-sqlite/README.md This JavaScript snippet shows how to use the Database class to insert data into SQLite and query it by ID. The operations are asynchronous, leveraging Rust's backend for database operations. ```JavaScript const Database = require("."); (async () => { const db = new Database(); const id = await db.insert("Marty McFly"); const name = await db.byId(id); console.log(name); })(); ``` -------------------------------- ### Create Runtime Helper Function for Neon Context in Rust Source: https://github.com/neon-bindings/examples/blob/main/examples/tokio-fetch/README.md Provides a helper that lazily initializes the global Tokio runtime and returns a reference suitable for Neon functions. It propagates initialization errors as JavaScript exceptions via the Neon context. This function abstracts runtime access for subsequent async calls. ```rust fn runtime<'a, C: Context<'a>>(cx: &mut C) -> NeonResult<&'static Runtime> { RUNTIME.get_or_try_init(|| Runtime::new().or_else(|err| cx.throw_error(err.to_string()))) } ``` -------------------------------- ### JavaScript Node.js Gzip Compression Stream with Neon Source: https://context7.com/neon-bindings/examples/llms.txt Implements a Node.js Transform stream that utilizes the Rust-based gzip compression addon. This JavaScript code defines the stream's transform and flush logic, integrating with the native `compressChunk` and `compressFinish` functions to process data chunks and finalize compression. ```javascript const { Transform } = require("stream"); const { compressNew, compressChunk, compressFinish } = require("./index.node"); const fs = require("fs"); function compress() { const compressor = compressNew(); return new Transform({ transform(chunk, encoding, callback) { compressChunk(compressor, encoding, chunk) .then(data => callback(null, data)) .catch(callback); }, flush(callback) { compressFinish(compressor) .then(data => callback(null, data)) .catch(callback); } }); } // Compress a file fs.createReadStream('input.txt') .pipe(compress()) .pipe(fs.createWriteStream('output.txt.gz')) .on('finish', () => console.log('Compression complete')); ``` -------------------------------- ### Consuming Async Rust Function in Node.js (JavaScript) Source: https://context7.com/neon-bindings/examples/llms.txt Calls an exported asynchronous function from a native Neon module to retrieve the release date of the current Node.js version. It uses `async/await` syntax for handling the promise returned by the native module. No specific dependencies are required beyond Node.js itself. ```javascript const { nodeReleaseDate } = require('./index.node'); async function getReleaseDate() { try { const releaseDate = await nodeReleaseDate(); console.log(`Current Node.js version was released on: ${releaseDate}`); // Output: Current Node.js version was released on: 2024-01-15 } catch (err) { console.error(`Error fetching release date: ${err.message}`); } } getReleaseDate(); ``` -------------------------------- ### Spawn Asynchronous Rust Task on Tokio Runtime in Neon Source: https://github.com/neon-bindings/examples/blob/main/examples/tokio-fetch/README.md Demonstrates acquiring the runtime via the helper and spawning an async block without blocking the JavaScript thread. The spawned task can perform any async Rust operations. Errors are propagated using the Neon result type. -------------------------------- ### Create Compress Transform Stream in JavaScript Source: https://github.com/neon-bindings/examples/blob/main/examples/gzip-stream/README.md This JavaScript function creates a Transform stream that delegates gzip compression to Neon Rust functions. It handles readable, writable, and backpressure features using Node.js Transform class. The function adapts promise-based Neon calls to the callback style expected by Transform. ```javascript function compress() { const compressor = compressNew(); return new Transform({ transform(chunk, encoding, callback) { compressChunk(compressor, encoding, chunk) .then(data => callback(null, data)) .catch(callback); }, flush(callback) { compressFinish(compressor) .then(data => callback(null, data)) .catch(callback); } }); } ``` -------------------------------- ### Create Neon Promise and Resolve from Tokio Async Task in Rust Source: https://github.com/neon-bindings/examples/blob/main/examples/tokio-fetch/README.md Shows how to create a Neon Promise and Deferred, spawn an async task on the Tokio runtime, and settle the promise from the JavaScript main thread using a Neon Channel. This pattern enables non‑blocking Rust code to communicate results back to JavaScript. ```rust let channel = cx.channel(); let (deferred, promise) = cx.promise(); rt.spawn(async move { // Code here executes non-blocking on the tokio thread pool deferred.settle_with(&channel, move |mut cx| { // Code here executes blocking on the JavaScript main thread Ok(cx.undefined()) }); }); Ok(promise) ``` -------------------------------- ### Initialize Tokio Runtime with OnceCell in Rust Source: https://github.com/neon-bindings/examples/blob/main/examples/tokio-fetch/README.md Sets up a global Tokio runtime using once_cell::sync::OnceCell to ensure a single runtime instance across Neon functions. This code runs at module load time and requires the once_cell and tokio crates. It prepares the runtime for later async task execution. ```rust use once_cell::sync::OnceCell; use tokio::runtime::Runtime; static RUNTIME: OnceCell = OnceCell::new(); ``` -------------------------------- ### Finish Compress Stream in Rust Source: https://github.com/neon-bindings/examples/blob/main/examples/gzip-stream/README.md This Rust function finalizes the gzip compression asynchronously, flushing any buffered data and calculating CRC using Neon. It operates similarly to compressChunk but without input data, completing the compressed output. The task runs on the worker pool, and the promise resolves with the final JsBuffer. ```rust fn compress_finish(mut cx: FunctionContext) -> JsResult { let stream = (&**cx.argument::>(0)?).clone(); let promise = cx .task(move || stream.finish()) .promise(CompressStream::and_buffer); Ok(promise) } ``` -------------------------------- ### Compress Data Chunk in Rust Source: https://github.com/neon-bindings/examples/blob/main/examples/gzip-stream/README.md This Rust function compresses a chunk of data asynchronously on Node's worker pool using Neon. It takes the CompressStream, chunk, and encoding, clones the data to Vec, and executes the task off the main thread. The promise resolves with compressed data converted to JsBuffer on the main thread. ```rust fn compress_chunk(mut cx: FunctionContext) -> JsResult { let stream = (&**cx.argument::>(0)?).clone(); let chunk = cx.argument::>(2)? .as_slice(&cx) .to_vec(); let promise = cx .task(move || stream.write(chunk)) .promise(CompressStream::and_buffer); Ok(promise) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.