Crate neon[−][src]
Expand description
The Neon crate provides bindings for writing Node.js addons (i.e., dynamically-loaded binary modules) with a safe and fast Rust API.
Getting Started
You can conveniently bootstrap a new Neon project with the Neon project generator. You don’t need to install anything special on your machine as long as you have a supported version of Node and Rust on your system.
To start a new project, open a terminal in the directory where you would like to place the project, and run at the command prompt:
% npm init neon my-project
... answer the user prompts ...
✨ Created Neon project `my-project`. Happy 🦀 hacking! ✨
where my-project
can be any name you like for the project. This will
run the Neon project generator, prompting you with a few questions and
placing a simple but working Neon project in a subdirectory called
my-project
(or whatever name you chose).
You can then install and build the project by changing into the project directory and running the standard Node installation command:
% cd my-project
% npm install
% node
> require(".").hello()
'hello node'
You can look in the project’s generated README.md
for more details on
the project structure.
Example
The generated src/lib.rs
contains a function annotated with the
#[neon::main]
attribute, marking it as the module’s main entry
point to be executed when the module is loaded. This function can have
any name but is conventionally called main
:
#[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("hello", hello)?; Ok(()) }
The example code generated by npm init neon
exports a single
function via ModuleContext::export_function
.
The hello
function is defined just above main
in src/lib.rs
:
fn hello(mut cx: FunctionContext) -> JsResult<JsString> { Ok(cx.string("hello node")) }
The hello
function takes a FunctionContext
and
returns a JavaScript string. Because all Neon functions can potentially throw a
JavaScript exception, the return type is wrapped in a JsResult
.
Modules
borrow | Provides temporary access to JavaScript typed arrays. |
context | Provides runtime access to the JavaScript engine. |
event | Exposes the JavaScript event loop for scheduling asynchronous events. |
handle | References to garbage-collected JavaScript values. |
meta | Metadata about the Neon version and build. |
object | Traits for working with JavaScript objects. |
prelude | Convenience module for the most common Neon imports. |
result | Represents JavaScript exceptions as a Rust |
task | Utilities for scheduling tasks to be executed by the Node.js runtime |
types | Representations of JavaScript’s core builtin types. |
Macros
declare_types | Declare custom native JavaScript types with Rust implementations. |
register_module | Register the current crate as a Node module, providing startup logic for initializing the module object at runtime. |
Attribute Macros
main | Marks a function as the main entry point for initialization in a Neon module. |