Skip to content

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

CallCreatesReturns
cx.number(x)numberHandle<JsNumber>
cx.string(s)stringHandle<JsString>
cx.boolean(b)booleanHandle<JsBoolean>
cx.null()nullHandle<JsNull>
cx.undefined()undefinedHandle<JsUndefined>
cx.empty_object(){}Handle<JsObject>
cx.empty_array()[]Handle<JsArray>
cx.buffer(n)?Node Buffer of n bytesHandle<JsBuffer>
cx.array_buffer(n)?ArrayBuffer of n bytesHandle<JsArrayBuffer>
cx.boxed(value)a JsBox wrapping Rust dataHandle<JsBox<T>>

Read arguments

CallDoes
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

CallDoes
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])

CallDoes
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

CallDoes
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

CallDoes
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.