Struct napi::Env

source · []
pub struct Env(_);
Expand description

Env is used to represent a context that the underlying N-API implementation can use to persist VM-specific state.

Specifically, the same Env that was passed in when the initial native function was called must be passed to any subsequent nested N-API calls.

Caching the Env for the purpose of general reuse, and passing the Env between instances of the same addon running on different Worker threads is not allowed.

The Env becomes invalid when an instance of a native addon is unloaded.

Notification of this event is delivered through the callbacks given to Env::add_env_cleanup_hook and Env::set_instance_data.

Implementations

Get JsUndefined value

n_api_napi_create_bigint_words

The resulting BigInt will be negative when sign_bit is true.

This API is used for C ffi scenario. Convert raw *const c_char into JsString

Safety

Create JsString from known valid utf-8 string

This API allocates a node::Buffer object. While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.

This API allocates a node::Buffer object and initializes it with data backed by the passed in buffer.

While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.

Safety

Mostly the same with create_buffer_with_data

Provided finalize_callback will be called when Buffer got dropped.

You can pass in noop_finalize if you have nothing to do in finalize phase.

This function gives V8 an indication of the amount of externally allocated memory that is kept alive by JavaScript objects (i.e. a JavaScript object that points to its own memory allocated by a native module).

Registering externally allocated memory will trigger global garbage collections more often than it would otherwise.

ATTENTION ⚠️, do not use this with create_buffer_with_data/create_arraybuffer_with_data, since these two functions already called the adjust_external_memory internal.

This API allocates a node::Buffer object and initializes it with data copied from the passed-in buffer.

While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.

Safety

Mostly the same with create_arraybuffer_with_data

Provided finalize_callback will be called when Buffer got dropped.

You can pass in noop_finalize if you have nothing to do in finalize phase.

This API allows an add-on author to create a function object in native code.

This is the primary mechanism to allow calling into the add-on’s native code from JavaScript.

The newly created function is not automatically visible from script after this call.

Instead, a property must be explicitly set on any object that is visible to JavaScript, in order for the function to be accessible from script.

This API retrieves a napi_extended_error_info structure with information about the last error that occurred.

The content of the napi_extended_error_info returned is only valid up until an n-api function is called on the same env.

Do not rely on the content or format of any of the extended information as it is not subject to SemVer and may change at any time. It is intended only for logging purposes.

This API can be called even if there is a pending JavaScript exception.

Throw any JavaScript value

This API throws a JavaScript Error with the text provided.

This API throws a JavaScript RangeError with the text provided.

This API throws a JavaScript TypeError with the text provided.

This API throws a JavaScript SyntaxError with the text provided.

In the event of an unrecoverable error in a native module

A fatal error can be thrown to immediately terminate the process.

Trigger an ‘uncaughtException’ in JavaScript.

Useful if an async callback throws an exception with no way to recover.

Create JavaScript class

This API create a new reference with the initial 1 ref count to the Object passed in.

This API create a new reference with the specified reference count to the Object passed in.

Get reference value from Ref with type check

Return error if the type of reference provided is mismatched with T

Get reference value from Ref without type check

Using this API if you are sure the type of T is matched with provided Ref<()>.

If type mismatched, calling T::method would return Err.

If size_hint provided, Env::adjust_external_memory will be called under the hood.

If no size_hint provided, global garbage collections will be triggered less times than expected.

If getting the exact native_object size is difficult, you can provide an approximate value, it’s only effect to the GC.

Run Task in libuv thread pool, return AsyncWorkPromise

This API does not observe leap seconds; they are ignored, as ECMAScript aligns with POSIX time specification.

This API allocates a JavaScript Date object.

JavaScript Date objects are described in Section 20.3 of the ECMAScript Language Specification.

This API associates data with the currently running Agent. data can later be retrieved using Env::get_instance_data().

Any existing data associated with the currently running Agent which was set by means of a previous call to Env::set_instance_data() will be overwritten.

If a finalize_cb was provided by the previous call, it will not be called.

This API retrieves data that was previously associated with the currently running Agent via Env::set_instance_data().

If no data is set, the call will succeed and data will be set to NULL.

Registers hook, which is a function of type FnOnce(Arg), as a function to be run with the arg parameter once the current Node.js environment exits.

Unlike add_env_cleanup_hook, the hook is allowed to be asynchronous.

Otherwise, behavior generally matches that of add_env_cleanup_hook.

This API is very similar to add_removable_async_cleanup_hook

Use this one if you don’t want remove the cleanup hook anymore.

Serialize Rust Struct into JavaScript Value
#[derive(Serialize, Debug, Deserialize)]
struct AnObject {
    a: u32,
    b: Vec<f64>,
    c: String,
}

#[js_function]
fn serialize(ctx: CallContext) -> Result<JsUnknown> {
    let value = AnyObject { a: 1, b: vec![0.1, 2.22], c: "hello" };
    ctx.env.to_js_value(&value)
}
Deserialize data from JsValue
#[derive(Serialize, Debug, Deserialize)]
struct AnObject {
    a: u32,
    b: Vec<f64>,
    c: String,
}

#[js_function(1)]
fn deserialize_from_js(ctx: CallContext) -> Result<JsUndefined> {
    let arg0 = ctx.get::<JsUnknown>(0)?;
    let de_serialized: AnObject = ctx.env.from_js_value(arg0)?;
    ...
}

This API represents the invocation of the Strict Equality algorithm as defined in Section 7.2.14 of the ECMAScript Language Specification.

get raw env ptr

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Converts to this type from the input type.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.