pub struct Env(/* private fields */);
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§
source§impl Env
impl Env
pub fn create_array(&self, len: u32) -> Result<Array>
sourcepub fn get_undefined(&self) -> Result<JsUndefined>
pub fn get_undefined(&self) -> Result<JsUndefined>
Get JsUndefined value
pub fn get_null(&self) -> Result<JsNull>
pub fn get_global(&self) -> Result<JsGlobal>
source§impl Env
impl Env
pub unsafe fn from_raw(env: napi_env) -> Self
pub fn get_boolean(&self, value: bool) -> Result<JsBoolean>
pub fn create_int32(&self, int: i32) -> Result<JsNumber>
pub fn create_int64(&self, int: i64) -> Result<JsNumber>
pub fn create_uint32(&self, number: u32) -> Result<JsNumber>
pub fn create_double(&self, double: f64) -> Result<JsNumber>
sourcepub fn create_bigint_from_i64(&self, value: i64) -> Result<JsBigInt>
pub fn create_bigint_from_i64(&self, value: i64) -> Result<JsBigInt>
pub fn create_bigint_from_u64(&self, value: u64) -> Result<JsBigInt>
pub fn create_bigint_from_i128(&self, value: i128) -> Result<JsBigInt>
pub fn create_bigint_from_u128(&self, value: u128) -> Result<JsBigInt>
sourcepub fn create_bigint_from_words(
&self,
sign_bit: bool,
words: Vec<u64>,
) -> Result<JsBigInt>
pub fn create_bigint_from_words( &self, sign_bit: bool, words: Vec<u64>, ) -> Result<JsBigInt>
n_api_napi_create_bigint_words
The resulting BigInt will be negative when sign_bit is true.
pub fn create_string(&self, s: &str) -> Result<JsString>
pub fn create_string_from_std(&self, s: String) -> Result<JsString>
sourcepub unsafe fn create_string_from_c_char(
&self,
data_ptr: *const c_char,
len: usize,
) -> Result<JsString>
pub unsafe fn create_string_from_c_char( &self, data_ptr: *const c_char, len: usize, ) -> Result<JsString>
This API is used for C ffi scenario. Convert raw *const c_char into JsString
§Safety
Create JsString from known valid utf-8 string
pub fn create_string_utf16(&self, chars: &[u16]) -> Result<JsString>
pub fn create_string_latin1(&self, chars: &[u8]) -> Result<JsString>
pub fn create_symbol_from_js_string( &self, description: JsString, ) -> Result<JsSymbol>
pub fn create_symbol(&self, description: Option<&str>) -> Result<JsSymbol>
pub fn create_object(&self) -> Result<JsObject>
pub fn create_empty_array(&self) -> Result<JsObject>
pub fn create_array_with_length(&self, length: usize) -> Result<JsObject>
sourcepub fn create_buffer(&self, length: usize) -> Result<JsBufferValue>
pub fn create_buffer(&self, length: usize) -> Result<JsBufferValue>
This API allocates a node::Buffer object. While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
sourcepub fn create_buffer_with_data(&self, data: Vec<u8>) -> Result<JsBufferValue>
pub fn create_buffer_with_data(&self, data: Vec<u8>) -> Result<JsBufferValue>
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.
sourcepub unsafe fn create_buffer_with_borrowed_data<Hint, Finalize>(
&self,
data: *mut u8,
length: usize,
hint: Hint,
finalize_callback: Finalize,
) -> Result<JsBufferValue>
pub unsafe fn create_buffer_with_borrowed_data<Hint, Finalize>( &self, data: *mut u8, length: usize, hint: Hint, finalize_callback: Finalize, ) -> Result<JsBufferValue>
§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.
§Notes
JavaScript may mutate the data passed in to this buffer when writing the buffer. However, some JavaScript runtimes do not support external buffers (notably electron!) in which case modifications may be lost.
If you need to support these runtimes, you should create a buffer by other means and then later copy the data back out.
sourcepub fn adjust_external_memory(&mut self, size: i64) -> Result<i64>
pub fn adjust_external_memory(&mut self, size: i64) -> Result<i64>
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.
sourcepub fn create_buffer_copy<D>(&self, data_to_copy: D) -> Result<JsBufferValue>
pub fn create_buffer_copy<D>(&self, data_to_copy: D) -> Result<JsBufferValue>
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.
pub fn create_arraybuffer(&self, length: usize) -> Result<JsArrayBufferValue>
pub fn create_arraybuffer_with_data( &self, data: Vec<u8>, ) -> Result<JsArrayBufferValue>
sourcepub unsafe fn create_arraybuffer_with_borrowed_data<Hint, Finalize>(
&self,
data: *mut u8,
length: usize,
hint: Hint,
finalize_callback: Finalize,
) -> Result<JsArrayBufferValue>
pub unsafe fn create_arraybuffer_with_borrowed_data<Hint, Finalize>( &self, data: *mut u8, length: usize, hint: Hint, finalize_callback: Finalize, ) -> Result<JsArrayBufferValue>
§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.
§Notes
JavaScript may mutate the data passed in to this buffer when writing the buffer. However, some JavaScript runtimes do not support external buffers (notably electron!) in which case modifications may be lost.
If you need to support these runtimes, you should create a buffer by other means and then later copy the data back out.
sourcepub fn create_function(
&self,
name: &str,
callback: Callback,
) -> Result<JsFunction>
pub fn create_function( &self, name: &str, callback: Callback, ) -> Result<JsFunction>
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.
pub fn create_function_from_closure<R, F>( &self, name: &str, callback: F, ) -> Result<JsFunction>
sourcepub fn get_last_error_info(&self) -> Result<ExtendedErrorInfo>
pub fn get_last_error_info(&self) -> Result<ExtendedErrorInfo>
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.
sourcepub fn throw_error(&self, msg: &str, code: Option<&str>) -> Result<()>
pub fn throw_error(&self, msg: &str, code: Option<&str>) -> Result<()>
This API throws a JavaScript Error with the text provided.
sourcepub fn throw_range_error(&self, msg: &str, code: Option<&str>) -> Result<()>
pub fn throw_range_error(&self, msg: &str, code: Option<&str>) -> Result<()>
This API throws a JavaScript RangeError with the text provided.
sourcepub fn throw_type_error(&self, msg: &str, code: Option<&str>) -> Result<()>
pub fn throw_type_error(&self, msg: &str, code: Option<&str>) -> Result<()>
This API throws a JavaScript TypeError with the text provided.
sourcepub fn throw_syntax_error<S: AsRef<str>, C: AsRef<str>>(
&self,
msg: S,
code: Option<C>,
)
pub fn throw_syntax_error<S: AsRef<str>, C: AsRef<str>>( &self, msg: S, code: Option<C>, )
This API throws a JavaScript SyntaxError with the text provided.
sourcepub fn fatal_error(self, location: &str, message: &str)
pub fn fatal_error(self, location: &str, message: &str)
In the event of an unrecoverable error in a native module
A fatal error can be thrown to immediately terminate the process.
sourcepub fn fatal_exception(&self, err: Error)
pub fn fatal_exception(&self, err: Error)
Trigger an ‘uncaughtException’ in JavaScript.
Useful if an async callback throws an exception with no way to recover.
sourcepub fn define_class(
&self,
name: &str,
constructor_cb: Callback,
properties: &[Property],
) -> Result<JsFunction>
pub fn define_class( &self, name: &str, constructor_cb: Callback, properties: &[Property], ) -> Result<JsFunction>
Create JavaScript class
pub fn wrap<T: 'static>( &self, js_object: &mut JsObject, native_object: T, ) -> Result<()>
pub fn unwrap<T: 'static>(&self, js_object: &JsObject) -> Result<&mut T>
pub fn drop_wrapped<T: 'static>(&self, js_object: &JsObject) -> Result<()>
sourcepub fn create_reference<T>(&self, value: T) -> Result<Ref<()>>where
T: NapiRaw,
pub fn create_reference<T>(&self, value: T) -> Result<Ref<()>>where
T: NapiRaw,
This API create a new reference with the initial 1 ref count to the Object passed in.
sourcepub fn create_reference_with_refcount<T>(
&self,
value: T,
ref_count: u32,
) -> Result<Ref<()>>where
T: NapiRaw,
pub fn create_reference_with_refcount<T>(
&self,
value: T,
ref_count: u32,
) -> Result<Ref<()>>where
T: NapiRaw,
This API create a new reference with the specified reference count to the Object passed in.
sourcepub fn get_reference_value<T>(&self, reference: &Ref<()>) -> Result<T>where
T: NapiValue,
pub fn get_reference_value<T>(&self, reference: &Ref<()>) -> Result<T>where
T: NapiValue,
Get reference value from Ref
with type check
Return error if the type of reference
provided is mismatched with T
sourcepub fn get_reference_value_unchecked<T>(&self, reference: &Ref<()>) -> Result<T>where
T: NapiValue,
pub fn get_reference_value_unchecked<T>(&self, reference: &Ref<()>) -> Result<T>where
T: NapiValue,
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
.
sourcepub fn create_external<T: 'static>(
&self,
native_object: T,
size_hint: Option<i64>,
) -> Result<JsExternal>
pub fn create_external<T: 'static>( &self, native_object: T, size_hint: Option<i64>, ) -> Result<JsExternal>
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.
pub fn get_value_external<T: 'static>( &self, js_external: &JsExternal, ) -> Result<&mut T>
pub fn create_error(&self, e: Error) -> Result<JsObject>
sourcepub fn spawn<T: 'static + Task>(&self, task: T) -> Result<AsyncWorkPromise>
pub fn spawn<T: 'static + Task>(&self, task: T) -> Result<AsyncWorkPromise>
Run Task in libuv thread pool, return AsyncWorkPromise
pub fn run_in_scope<T, F>(&self, executor: F) -> Result<T>
sourcepub fn run_script<S: AsRef<str>, V: FromNapiValue>(
&self,
script: S,
) -> Result<V>
pub fn run_script<S: AsRef<str>, V: FromNapiValue>( &self, script: S, ) -> Result<V>
Node-API provides an API for executing a string containing JavaScript using the underlying JavaScript engine. This function executes a string of JavaScript code and returns its result with the following caveats:
- Unlike
eval
, this function does not allow the script to access the current lexical scope, and therefore also does not allow to access the module scope, meaning that pseudo-globals such as require will not be available. - The script can access the global scope. Function and
var
declarations in the script will be added to the global object. Variable declarations made usinglet
andconst
will be visible globally, but will not be added to the global object. - The value of this is global within the script.
sourcepub fn get_napi_version(&self) -> Result<u32>
pub fn get_napi_version(&self) -> Result<u32>
process.versions.napi
pub fn get_uv_event_loop(&self) -> Result<*mut uv_loop_s>
pub fn add_env_cleanup_hook<T, F>(
&mut self,
cleanup_data: T,
cleanup_fn: F,
) -> Result<CleanupEnvHook<T>>where
T: 'static,
F: 'static + FnOnce(T),
pub fn remove_env_cleanup_hook<T>(
&mut self,
hook: CleanupEnvHook<T>,
) -> Result<()>where
T: 'static,
pub fn create_threadsafe_function<T: Send, V: ToNapiValue, R: 'static + Send + FnMut(ThreadSafeCallContext<T>) -> Result<Vec<V>>>( &self, func: &JsFunction, max_queue_size: usize, callback: R, ) -> Result<ThreadsafeFunction<T>>
pub fn execute_tokio_future<T: 'static + Send, V: 'static + ToNapiValue, F: 'static + Send + Future<Output = Result<T>>, R: 'static + FnOnce(&mut Env, T) -> Result<V>>( &self, fut: F, resolver: R, ) -> Result<JsObject>
pub fn spawn_future<T: 'static + Send + ToNapiValue, F: 'static + Send + Future<Output = Result<T>>>( &self, fut: F, ) -> Result<JsObject>
sourcepub fn create_deferred<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>>(
&self,
) -> Result<(JsDeferred<Data, Resolver>, JsObject)>
pub fn create_deferred<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>>( &self, ) -> Result<(JsDeferred<Data, Resolver>, JsObject)>
Creates a deferred promise, which can be resolved or rejected from a background thread.
sourcepub fn create_date(&self, time: f64) -> Result<JsDate>
pub fn create_date(&self, time: f64) -> Result<JsDate>
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.
sourcepub fn set_instance_data<T, Hint, F>(
&self,
native: T,
hint: Hint,
finalize_cb: F,
) -> Result<()>where
T: 'static,
Hint: 'static,
F: FnOnce(FinalizeContext<T, Hint>),
pub fn set_instance_data<T, Hint, F>(
&self,
native: T,
hint: Hint,
finalize_cb: F,
) -> Result<()>where
T: 'static,
Hint: 'static,
F: FnOnce(FinalizeContext<T, Hint>),
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.
sourcepub fn get_instance_data<T>(&self) -> Result<Option<&'static mut T>>where
T: 'static,
pub fn get_instance_data<T>(&self) -> Result<Option<&'static mut T>>where
T: 'static,
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.
sourcepub fn add_removable_async_cleanup_hook<Arg, F>(
&self,
arg: Arg,
cleanup_fn: F,
) -> Result<AsyncCleanupHook>where
F: FnOnce(Arg),
Arg: 'static,
pub fn add_removable_async_cleanup_hook<Arg, F>(
&self,
arg: Arg,
cleanup_fn: F,
) -> Result<AsyncCleanupHook>where
F: FnOnce(Arg),
Arg: 'static,
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
.
sourcepub fn add_async_cleanup_hook<Arg, F>(
&self,
arg: Arg,
cleanup_fn: F,
) -> Result<()>where
F: FnOnce(Arg),
Arg: 'static,
pub fn add_async_cleanup_hook<Arg, F>(
&self,
arg: Arg,
cleanup_fn: F,
) -> Result<()>where
F: FnOnce(Arg),
Arg: 'static,
This API is very similar to add_removable_async_cleanup_hook
Use this one if you don’t want remove the cleanup hook anymore.
pub fn symbol_for(&self, description: &str) -> Result<JsSymbol>
sourcepub fn get_module_file_name(&self) -> Result<String>
pub fn get_module_file_name(&self) -> Result<String>
This API retrieves the file path of the currently running JS module as a URL. For a file on
the local file system it will start with file://
.
§Errors
The retrieved string may be empty if the add-on loading process fails to establish the add-on’s file name.
sourcepub fn to_js_value<T>(&self, node: &T) -> Result<JsUnknown>where
T: Serialize,
pub fn to_js_value<T>(&self, node: &T) -> Result<JsUnknown>where
T: Serialize,
§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)
}
sourcepub fn from_js_value<T, V>(&self, value: V) -> Result<T>where
T: DeserializeOwned,
V: NapiRaw,
pub fn from_js_value<T, V>(&self, value: V) -> Result<T>where
T: DeserializeOwned,
V: NapiRaw,
§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)?;
...
}
sourcepub fn strict_equals<A: NapiRaw, B: NapiRaw>(&self, a: A, b: B) -> Result<bool>
pub fn strict_equals<A: NapiRaw, B: NapiRaw>(&self, a: A, b: B) -> Result<bool>
This API represents the invocation of the Strict Equality algorithm as defined in Section 7.2.14 of the ECMAScript Language Specification.
pub fn get_node_version(&self) -> Result<NodeVersion>
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Env
impl RefUnwindSafe for Env
impl !Send for Env
impl !Sync for Env
impl Unpin for Env
impl UnwindSafe for Env
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)