Appearance
Context (cx) Methods
Fresh 🌱The context (cx) is your handle to the JavaScript runtime. This is a cheat sheet of the methods you reach for most. (Method availability depends on the context type - FunctionContext, ModuleContext, etc. - and the enabled features.)
Construct JavaScript values
| Call | Creates | Returns |
|---|---|---|
cx.number(x) | number | Handle<JsNumber> |
cx.string(s) | string | Handle<JsString> |
cx.boolean(b) | boolean | Handle<JsBoolean> |
cx.null() | null | Handle<JsNull> |
cx.undefined() | undefined | Handle<JsUndefined> |
cx.empty_object() | {} | Handle<JsObject> |
cx.empty_array() | [] | Handle<JsArray> |
cx.buffer(n)? | Node Buffer of n bytes | Handle<JsBuffer> |
cx.array_buffer(n)? | ArrayBuffer of n bytes | Handle<JsArrayBuffer> |
cx.boxed(value) | a JsBox wrapping Rust data | Handle<JsBox<T>> |
Read arguments
| Call | Does |
|---|---|
cx.argument::<JsString>(0)? | read & type-check positional arg 0 (throws TypeError on mismatch) |
cx.argument_opt(3) | read an argument that may be absent → Option<Handle<JsValue>> |
cx.args()? | (with #[neon::export]) destructure all args into a Rust tuple |
cx.args_opt::<(f64, f64)>()? | try to destructure args, returning Option for overloading |
Access the runtime
| Call | Does |
|---|---|
cx.global("Array")? | get a global value by name |
cx.global() | get the global object (then .get(&mut cx, "name")?) |
cx.this() | the this value of the call |
cx.lock() | acquire a lock for safe typed-array slice access |
Exports (in #[neon::main])
| Call | Does |
|---|---|
cx.export_function("name", f)? | export a Rust function under a JS name |
cx.export_value("name", v)? | export a constant or prebuilt value |
neon::registered().export(&mut cx)? | export everything tagged with #[neon::export] |
Async & threading
| Call | Does |
|---|---|
cx.task(|| ...) | run a closure on the worker pool, then .promise(...) |
cx.promise() | create a (Deferred, Promise) pair to settle later |
cx.channel() | get a Channel to schedule closures back on the main thread |
handle.root(&mut cx) | persist a JS value as a Root across threads/async |
root.into_inner(&mut cx) | turn a Root back into a Handle (on the main thread) |
Throw errors
| Call | Does |
|---|---|
cx.throw_error("msg") | throw a JS Error; returns an Err result |
result.or_throw(&mut cx)? | convert a Rust Result Err into a thrown JS exception |
Reach for the prelude
use neon::prelude::*; brings the common traits and types (Context, Handle, the Js* types, JsResult, NeonResult) into scope so these methods resolve.