content large_stringlengths 3 20.5k | url large_stringlengths 54 193 | branch large_stringclasses 4 values | source large_stringclasses 42 values | embeddings listlengths 384 384 | score float64 -0.21 0.65 |
|---|---|---|---|---|---|
VM specific error code. \* `error\_code`: Node-API status code for the last error. [`napi\_get\_last\_error\_info`][] returns the information for the last Node-API call that was made. 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. #### `napi\_get\_last\_error\_info` ```c napi\_status napi\_get\_last\_error\_info(node\_api\_basic\_env env, const napi\_extended\_error\_info\*\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: The `napi\_extended\_error\_info` structure with more information about the error. Returns `napi\_ok` if the API succeeded. 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 a Node-API function is called on the same `env`. This includes a call to `napi\_is\_exception\_pending` so it may often be necessary to make a copy of the information so that it can be used later. The pointer returned in `error\_message` points to a statically-defined string so it is safe to use that pointer if you have copied it out of the `error\_message` field (which will be overwritten) before another Node-API function was called. 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. ### Exceptions Any Node-API function call may result in a pending JavaScript exception. This is the case for any of the API functions, even those that may not cause the execution of JavaScript. If the `napi\_status` returned by a function is `napi\_ok` then no exception is pending and no additional action is required. If the `napi\_status` returned is anything other than `napi\_ok` or `napi\_pending\_exception`, in order to try to recover and continue instead of simply returning immediately, [`napi\_is\_exception\_pending`][] must be called in order to determine if an exception is pending or not. In many cases when a Node-API function is called and an exception is already pending, the function will return immediately with a `napi\_status` of `napi\_pending\_exception`. However, this is not the case for all functions. Node-API allows a subset of the functions to be called to allow for some minimal cleanup before returning to JavaScript. In that case, `napi\_status` will reflect the status for the function. It will not reflect previous pending exceptions. To avoid confusion, check the error status after every function call. When an exception is pending one of two approaches can be employed. The first approach is to do any appropriate cleanup and then return so that execution will return to JavaScript. As part of the transition back to JavaScript, the exception will be thrown at the point in the JavaScript code where the native method was invoked. The behavior of most Node-API calls is unspecified while an exception is pending, and many will simply return `napi\_pending\_exception`, so do as little as possible and then return to JavaScript where the exception can be handled. The second approach is to try to handle the exception. There will be cases where the native code can catch the exception, take the appropriate action, and then continue. This is only recommended in specific cases where it is known that the exception can be safely handled. In these cases [`napi\_get\_and\_clear\_last\_exception`][] can be used to get and clear the exception. On success, result will contain the handle to the last JavaScript `Object` thrown. If it is determined, after retrieving the exception, the exception cannot be handled after all it | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.021562889218330383,
0.11380654573440552,
-0.013727911747992039,
0.02253233641386032,
0.056688107550144196,
-0.04979275166988373,
-0.030227702111005783,
0.059605974704027176,
-0.03866162896156311,
0.0012572072446346283,
0.008759874850511551,
-0.056856974959373474,
0.010948900133371353,
-0... | 0.189219 |
known that the exception can be safely handled. In these cases [`napi\_get\_and\_clear\_last\_exception`][] can be used to get and clear the exception. On success, result will contain the handle to the last JavaScript `Object` thrown. If it is determined, after retrieving the exception, the exception cannot be handled after all it can be re-thrown it with [`napi\_throw`][] where error is the JavaScript value to be thrown. The following utility functions are also available in case native code needs to throw an exception or determine if a `napi\_value` is an instance of a JavaScript `Error` object: [`napi\_throw\_error`][], [`napi\_throw\_type\_error`][], [`napi\_throw\_range\_error`][], [`node\_api\_throw\_syntax\_error`][] and [`napi\_is\_error`][]. The following utility functions are also available in case native code needs to create an `Error` object: [`napi\_create\_error`][], [`napi\_create\_type\_error`][], [`napi\_create\_range\_error`][] and [`node\_api\_create\_syntax\_error`][], where result is the `napi\_value` that refers to the newly created JavaScript `Error` object. The Node.js project is adding error codes to all of the errors generated internally. The goal is for applications to use these error codes for all error checking. The associated error messages will remain, but will only be meant to be used for logging and display with the expectation that the message can change without SemVer applying. In order to support this model with Node-API, both in internal functionality and for module specific functionality (as its good practice), the `throw\_` and `create\_` functions take an optional code parameter which is the string for the code to be added to the error object. If the optional parameter is `NULL` then no code will be associated with the error. If a code is provided, the name associated with the error is also updated to be: ```text originalName [code] ``` where `originalName` is the original name associated with the error and `code` is the code that was provided. For example, if the code is `'ERR\_ERROR\_1'` and a `TypeError` is being created the name will be: ```text TypeError [ERR\_ERROR\_1] ``` #### `napi\_throw` ```c NAPI\_EXTERN napi\_status napi\_throw(napi\_env env, napi\_value error); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] error`: The JavaScript value to be thrown. Returns `napi\_ok` if the API succeeded. This API throws the JavaScript value provided. #### `napi\_throw\_error` ```c NAPI\_EXTERN napi\_status napi\_throw\_error(napi\_env env, const char\* code, const char\* msg); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] code`: Optional error code to be set on the error. \* `[in] msg`: C string representing the text to be associated with the error. Returns `napi\_ok` if the API succeeded. This API throws a JavaScript `Error` with the text provided. #### `napi\_throw\_type\_error` ```c NAPI\_EXTERN napi\_status napi\_throw\_type\_error(napi\_env env, const char\* code, const char\* msg); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] code`: Optional error code to be set on the error. \* `[in] msg`: C string representing the text to be associated with the error. Returns `napi\_ok` if the API succeeded. This API throws a JavaScript `TypeError` with the text provided. #### `napi\_throw\_range\_error` ```c NAPI\_EXTERN napi\_status napi\_throw\_range\_error(napi\_env env, const char\* code, const char\* msg); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] code`: Optional error code to be set on the error. \* `[in] msg`: C string representing the text to be associated with the error. Returns `napi\_ok` if the API succeeded. This API throws a JavaScript `RangeError` with the text provided. #### `node\_api\_throw\_syntax\_error` ```c NAPI\_EXTERN napi\_status node\_api\_throw\_syntax\_error(napi\_env env, const char\* code, const char\* msg); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] code`: Optional error code to be set on the error. \* `[in] msg`: C string representing the | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.03428228944540024,
0.11722787469625473,
0.01689343899488449,
0.029336251318454742,
0.00882340781390667,
-0.0033079986460506916,
0.021174311637878418,
0.019546041265130043,
-0.004901915788650513,
-0.07571747153997421,
-0.02739619091153145,
-0.01639418676495552,
0.009678197093307972,
-0.0... | 0.163582 |
JavaScript `RangeError` with the text provided. #### `node\_api\_throw\_syntax\_error` ```c NAPI\_EXTERN napi\_status node\_api\_throw\_syntax\_error(napi\_env env, const char\* code, const char\* msg); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] code`: Optional error code to be set on the error. \* `[in] msg`: C string representing the text to be associated with the error. Returns `napi\_ok` if the API succeeded. This API throws a JavaScript `SyntaxError` with the text provided. #### `napi\_is\_error` ```c NAPI\_EXTERN napi\_status napi\_is\_error(napi\_env env, napi\_value value, bool\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The `napi\_value` to be checked. \* `[out] result`: Boolean value that is set to true if `napi\_value` represents an error, false otherwise. Returns `napi\_ok` if the API succeeded. This API queries a `napi\_value` to check if it represents an error object. #### `napi\_create\_error` ```c NAPI\_EXTERN napi\_status napi\_create\_error(napi\_env env, napi\_value code, napi\_value msg, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] code`: Optional `napi\_value` with the string for the error code to be associated with the error. \* `[in] msg`: `napi\_value` that references a JavaScript `string` to be used as the message for the `Error`. \* `[out] result`: `napi\_value` representing the error created. Returns `napi\_ok` if the API succeeded. This API returns a JavaScript `Error` with the text provided. #### `napi\_create\_type\_error` ```c NAPI\_EXTERN napi\_status napi\_create\_type\_error(napi\_env env, napi\_value code, napi\_value msg, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] code`: Optional `napi\_value` with the string for the error code to be associated with the error. \* `[in] msg`: `napi\_value` that references a JavaScript `string` to be used as the message for the `Error`. \* `[out] result`: `napi\_value` representing the error created. Returns `napi\_ok` if the API succeeded. This API returns a JavaScript `TypeError` with the text provided. #### `napi\_create\_range\_error` ```c NAPI\_EXTERN napi\_status napi\_create\_range\_error(napi\_env env, napi\_value code, napi\_value msg, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] code`: Optional `napi\_value` with the string for the error code to be associated with the error. \* `[in] msg`: `napi\_value` that references a JavaScript `string` to be used as the message for the `Error`. \* `[out] result`: `napi\_value` representing the error created. Returns `napi\_ok` if the API succeeded. This API returns a JavaScript `RangeError` with the text provided. #### `node\_api\_create\_syntax\_error` ```c NAPI\_EXTERN napi\_status node\_api\_create\_syntax\_error(napi\_env env, napi\_value code, napi\_value msg, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] code`: Optional `napi\_value` with the string for the error code to be associated with the error. \* `[in] msg`: `napi\_value` that references a JavaScript `string` to be used as the message for the `Error`. \* `[out] result`: `napi\_value` representing the error created. Returns `napi\_ok` if the API succeeded. This API returns a JavaScript `SyntaxError` with the text provided. #### `napi\_get\_and\_clear\_last\_exception` ```c napi\_status napi\_get\_and\_clear\_last\_exception(napi\_env env, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: The exception if one is pending, `NULL` otherwise. Returns `napi\_ok` if the API succeeded. This API can be called even if there is a pending JavaScript exception. #### `napi\_is\_exception\_pending` ```c napi\_status napi\_is\_exception\_pending(napi\_env env, bool\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: Boolean value that is set to true if an exception is pending. Returns `napi\_ok` if the API succeeded. This API can be called even if there is a pending JavaScript exception. #### `napi\_fatal\_exception` ```c napi\_status napi\_fatal\_exception(napi\_env env, napi\_value err); ``` \* `[in] env`: The environment that the | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.022507822141051292,
0.10336222499608994,
0.013831653632223606,
0.014330293983221054,
0.009381204843521118,
-0.004403502214699984,
0.042607225477695465,
0.0796755775809288,
-0.046941760927438736,
-0.09236537665128708,
-0.02747334912419319,
-0.06926190108060837,
0.07621864974498749,
0.012... | 0.159746 |
\* `[out] result`: Boolean value that is set to true if an exception is pending. Returns `napi\_ok` if the API succeeded. This API can be called even if there is a pending JavaScript exception. #### `napi\_fatal\_exception` ```c napi\_status napi\_fatal\_exception(napi\_env env, napi\_value err); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] err`: The error that is passed to `'uncaughtException'`. Trigger an `'uncaughtException'` in JavaScript. Useful if an async callback throws an exception with no way to recover. ### Fatal errors In the event of an unrecoverable error in a native addon, a fatal error can be thrown to immediately terminate the process. #### `napi\_fatal\_error` ```c NAPI\_NO\_RETURN void napi\_fatal\_error(const char\* location, size\_t location\_len, const char\* message, size\_t message\_len); ``` \* `[in] location`: Optional location at which the error occurred. \* `[in] location\_len`: The length of the location in bytes, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[in] message`: The message associated with the error. \* `[in] message\_len`: The length of the message in bytes, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. The function call does not return, the process will be terminated. This API can be called even if there is a pending JavaScript exception. ## Object lifetime management As Node-API calls are made, handles to objects in the heap for the underlying VM may be returned as `napi\_values`. These handles must hold the objects 'live' until they are no longer required by the native code, otherwise the objects could be collected before the native code was finished using them. As object handles are returned they are associated with a 'scope'. The lifespan for the default scope is tied to the lifespan of the native method call. The result is that, by default, handles remain valid and the objects associated with these handles will be held live for the lifespan of the native method call. In many cases, however, it is necessary that the handles remain valid for either a shorter or longer lifespan than that of the native method. The sections which follow describe the Node-API functions that can be used to change the handle lifespan from the default. ### Making handle lifespan shorter than that of the native method It is often necessary to make the lifespan of handles shorter than the lifespan of a native method. For example, consider a native method that has a loop which iterates through the elements in a large array: ```c for (int i = 0; i < 1000000; i++) { napi\_value result; napi\_status status = napi\_get\_element(env, object, i, &result); if (status != napi\_ok) { break; } // do something with element } ``` This would result in a large number of handles being created, consuming substantial resources. In addition, even though the native code could only use the most recent handle, all of the associated objects would also be kept alive since they all share the same scope. To handle this case, Node-API provides the ability to establish a new 'scope' to which newly created handles will be associated. Once those handles are no longer required, the scope can be 'closed' and any handles associated with the scope are invalidated. The methods available to open/close scopes are [`napi\_open\_handle\_scope`][] and [`napi\_close\_handle\_scope`][]. Node-API only supports a single nested hierarchy of scopes. There is only one active scope at any time, and all new handles will be associated with that scope while it is active. Scopes must be closed in the reverse order from which they are opened. In addition, all scopes created within a native method must be closed before returning from that method. Taking the earlier example, adding calls | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.06448444724082947,
0.10399181395769119,
-0.017484517768025398,
0.044139374047517776,
0.019132070243358612,
-0.0028015687130391598,
0.0340949110686779,
0.05191684141755104,
-0.002960186917334795,
-0.0514821894466877,
0.007509813643991947,
-0.015392687171697617,
0.012092151679098606,
0.00... | 0.221266 |
and all new handles will be associated with that scope while it is active. Scopes must be closed in the reverse order from which they are opened. In addition, all scopes created within a native method must be closed before returning from that method. Taking the earlier example, adding calls to [`napi\_open\_handle\_scope`][] and [`napi\_close\_handle\_scope`][] would ensure that at most a single handle is valid throughout the execution of the loop: ```c for (int i = 0; i < 1000000; i++) { napi\_handle\_scope scope; napi\_status status = napi\_open\_handle\_scope(env, &scope); if (status != napi\_ok) { break; } napi\_value result; status = napi\_get\_element(env, object, i, &result); if (status != napi\_ok) { break; } // do something with element status = napi\_close\_handle\_scope(env, scope); if (status != napi\_ok) { break; } } ``` When nesting scopes, there are cases where a handle from an inner scope needs to live beyond the lifespan of that scope. Node-API supports an 'escapable scope' in order to support this case. An escapable scope allows one handle to be 'promoted' so that it 'escapes' the current scope and the lifespan of the handle changes from the current scope to that of the outer scope. The methods available to open/close escapable scopes are [`napi\_open\_escapable\_handle\_scope`][] and [`napi\_close\_escapable\_handle\_scope`][]. The request to promote a handle is made through [`napi\_escape\_handle`][] which can only be called once. #### `napi\_open\_handle\_scope` ```c NAPI\_EXTERN napi\_status napi\_open\_handle\_scope(napi\_env env, napi\_handle\_scope\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: `napi\_value` representing the new scope. Returns `napi\_ok` if the API succeeded. This API opens a new scope. #### `napi\_close\_handle\_scope` ```c NAPI\_EXTERN napi\_status napi\_close\_handle\_scope(napi\_env env, napi\_handle\_scope scope); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] scope`: `napi\_value` representing the scope to be closed. Returns `napi\_ok` if the API succeeded. This API closes the scope passed in. Scopes must be closed in the reverse order from which they were created. This API can be called even if there is a pending JavaScript exception. #### `napi\_open\_escapable\_handle\_scope` ```c NAPI\_EXTERN napi\_status napi\_open\_escapable\_handle\_scope(napi\_env env, napi\_handle\_scope\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: `napi\_value` representing the new scope. Returns `napi\_ok` if the API succeeded. This API opens a new scope from which one object can be promoted to the outer scope. #### `napi\_close\_escapable\_handle\_scope` ```c NAPI\_EXTERN napi\_status napi\_close\_escapable\_handle\_scope(napi\_env env, napi\_handle\_scope scope); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] scope`: `napi\_value` representing the scope to be closed. Returns `napi\_ok` if the API succeeded. This API closes the scope passed in. Scopes must be closed in the reverse order from which they were created. This API can be called even if there is a pending JavaScript exception. #### `napi\_escape\_handle` ```c napi\_status napi\_escape\_handle(napi\_env env, napi\_escapable\_handle\_scope scope, napi\_value escapee, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] scope`: `napi\_value` representing the current scope. \* `[in] escapee`: `napi\_value` representing the JavaScript `Object` to be escaped. \* `[out] result`: `napi\_value` representing the handle to the escaped `Object` in the outer scope. Returns `napi\_ok` if the API succeeded. This API promotes the handle to the JavaScript object so that it is valid for the lifetime of the outer scope. It can only be called once per scope. If it is called more than once an error will be returned. This API can be called even if there is a pending JavaScript exception. ### References to values with a lifespan longer than that of the native method In some cases, an addon will need to be able to create and reference | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.021275341510772705,
0.07705707103013992,
-0.04913349822163582,
0.01663612201809883,
-0.0942552238702774,
-0.06710422784090042,
0.0637572854757309,
-0.016365543007850647,
-0.039733320474624634,
0.001293642446398735,
-0.02857605181634426,
-0.01592188887298107,
-0.05400075018405914,
-0.0409... | 0.143863 |
called more than once an error will be returned. This API can be called even if there is a pending JavaScript exception. ### References to values with a lifespan longer than that of the native method In some cases, an addon will need to be able to create and reference values with a lifespan longer than that of a single native method invocation. For example, to create a constructor and later use that constructor in a request to create instances, it must be possible to reference the constructor object across many different instance creation requests. This would not be possible with a normal handle returned as a `napi\_value` as described in the earlier section. The lifespan of a normal handle is managed by scopes and all scopes must be closed before the end of a native method. Node-API provides methods for creating persistent references to values. Currently Node-API only allows references to be created for a limited set of value types, including object, external, function, and symbol. Each reference has an associated count with a value of 0 or higher, which determines whether the reference will keep the corresponding value alive. References with a count of 0 do not prevent values from being collected. Values of object (object, function, external) and symbol types are becoming 'weak' references and can still be accessed while they are not collected. Any count greater than 0 will prevent the values from being collected. Symbol values have different flavors. The true weak reference behavior is only supported by local symbols created with the `napi\_create\_symbol` function or the JavaScript `Symbol()` constructor calls. Globally registered symbols created with the `node\_api\_symbol\_for` function or JavaScript `Symbol.for()` function calls remain always strong references because the garbage collector does not collect them. The same is true for well-known symbols such as `Symbol.iterator`. They are also never collected by the garbage collector. References can be created with an initial reference count. The count can then be modified through [`napi\_reference\_ref`][] and [`napi\_reference\_unref`][]. If an object is collected while the count for a reference is 0, all subsequent calls to get the object associated with the reference [`napi\_get\_reference\_value`][] will return `NULL` for the returned `napi\_value`. An attempt to call [`napi\_reference\_ref`][] for a reference whose object has been collected results in an error. References must be deleted once they are no longer required by the addon. When a reference is deleted, it will no longer prevent the corresponding object from being collected. Failure to delete a persistent reference results in a 'memory leak' with both the native memory for the persistent reference and the corresponding object on the heap being retained forever. There can be multiple persistent references created which refer to the same object, each of which will either keep the object live or not based on its individual count. Multiple persistent references to the same object can result in unexpectedly keeping alive native memory. The native structures for a persistent reference must be kept alive until finalizers for the referenced object are executed. If a new persistent reference is created for the same object, the finalizers for that object will not be run and the native memory pointed by the earlier persistent reference will not be freed. This can be avoided by calling `napi\_delete\_reference` in addition to `napi\_reference\_unref` when possible. \*\*Change History:\*\* \* Version 10 (`NAPI\_VERSION` is defined as `10` or higher): References can be created for all value types. The new supported value types do not support weak reference semantic and the values of these types are released when the reference count becomes 0 and cannot be accessed from the reference anymore. | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.10944294184446335,
0.052229270339012146,
-0.02612912282347679,
0.10756006091833115,
-0.05172443389892578,
-0.05703900009393692,
-0.011777136474847794,
0.0026629031635820866,
0.10064515471458435,
-0.024186812341213226,
-0.04802807420492172,
-0.0030923422891646624,
-0.010227062739431858,
... | 0.15574 |
Version 10 (`NAPI\_VERSION` is defined as `10` or higher): References can be created for all value types. The new supported value types do not support weak reference semantic and the values of these types are released when the reference count becomes 0 and cannot be accessed from the reference anymore. #### `napi\_create\_reference` ```c NAPI\_EXTERN napi\_status napi\_create\_reference(napi\_env env, napi\_value value, uint32\_t initial\_refcount, napi\_ref\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The `napi\_value` for which a reference is being created. \* `[in] initial\_refcount`: Initial reference count for the new reference. \* `[out] result`: `napi\_ref` pointing to the new reference. Returns `napi\_ok` if the API succeeded. This API creates a new reference with the specified reference count to the value passed in. #### `napi\_delete\_reference` ```c NAPI\_EXTERN napi\_status napi\_delete\_reference(napi\_env env, napi\_ref ref); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] ref`: `napi\_ref` to be deleted. Returns `napi\_ok` if the API succeeded. This API deletes the reference passed in. This API can be called even if there is a pending JavaScript exception. #### `napi\_reference\_ref` ```c NAPI\_EXTERN napi\_status napi\_reference\_ref(napi\_env env, napi\_ref ref, uint32\_t\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] ref`: `napi\_ref` for which the reference count will be incremented. \* `[out] result`: The new reference count. Returns `napi\_ok` if the API succeeded. This API increments the reference count for the reference passed in and returns the resulting reference count. #### `napi\_reference\_unref` ```c NAPI\_EXTERN napi\_status napi\_reference\_unref(napi\_env env, napi\_ref ref, uint32\_t\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] ref`: `napi\_ref` for which the reference count will be decremented. \* `[out] result`: The new reference count. Returns `napi\_ok` if the API succeeded. This API decrements the reference count for the reference passed in and returns the resulting reference count. #### `napi\_get\_reference\_value` ```c NAPI\_EXTERN napi\_status napi\_get\_reference\_value(napi\_env env, napi\_ref ref, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] ref`: The `napi\_ref` for which the corresponding value is being requested. \* `[out] result`: The `napi\_value` referenced by the `napi\_ref`. Returns `napi\_ok` if the API succeeded. If still valid, this API returns the `napi\_value` representing the JavaScript value associated with the `napi\_ref`. Otherwise, result will be `NULL`. ### Cleanup on exit of the current Node.js environment While a Node.js process typically releases all its resources when exiting, embedders of Node.js, or future Worker support, may require addons to register clean-up hooks that will be run once the current Node.js environment exits. Node-API provides functions for registering and un-registering such callbacks. When those callbacks are run, all resources that are being held by the addon should be freed up. #### `napi\_add\_env\_cleanup\_hook` ```c NODE\_EXTERN napi\_status napi\_add\_env\_cleanup\_hook(node\_api\_basic\_env env, napi\_cleanup\_hook fun, void\* arg); ``` Registers `fun` as a function to be run with the `arg` parameter once the current Node.js environment exits. A function can safely be specified multiple times with different `arg` values. In that case, it will be called multiple times as well. Providing the same `fun` and `arg` values multiple times is not allowed and will lead the process to abort. The hooks will be called in reverse order, i.e. the most recently added one will be called first. Removing this hook can be done by using [`napi\_remove\_env\_cleanup\_hook`][]. Typically, that happens when the resource for which this hook was added is being torn down anyway. For asynchronous cleanup, [`napi\_add\_async\_cleanup\_hook`][] is available. #### `napi\_remove\_env\_cleanup\_hook` ```c NAPI\_EXTERN napi\_status napi\_remove\_env\_cleanup\_hook(node\_api\_basic\_env env, void (\*fun)(void\* arg), void\* arg); ``` Unregisters `fun` as a function to be run with the | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.058812275528907776,
0.02768278680741787,
-0.08434447646141052,
-0.01406378485262394,
-0.04927736148238182,
-0.0005101261776871979,
0.03551929444074631,
0.01236431859433651,
-0.003494862699881196,
-0.07163098454475403,
-0.003027914557605982,
-0.09013349562883377,
0.02341427467763424,
0.0... | 0.2173 |
done by using [`napi\_remove\_env\_cleanup\_hook`][]. Typically, that happens when the resource for which this hook was added is being torn down anyway. For asynchronous cleanup, [`napi\_add\_async\_cleanup\_hook`][] is available. #### `napi\_remove\_env\_cleanup\_hook` ```c NAPI\_EXTERN napi\_status napi\_remove\_env\_cleanup\_hook(node\_api\_basic\_env env, void (\*fun)(void\* arg), void\* arg); ``` Unregisters `fun` as a function to be run with the `arg` parameter once the current Node.js environment exits. Both the argument and the function value need to be exact matches. The function must have originally been registered with `napi\_add\_env\_cleanup\_hook`, otherwise the process will abort. #### `napi\_add\_async\_cleanup\_hook` ```c NAPI\_EXTERN napi\_status napi\_add\_async\_cleanup\_hook( node\_api\_basic\_env env, napi\_async\_cleanup\_hook hook, void\* arg, napi\_async\_cleanup\_hook\_handle\* remove\_handle); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] hook`: The function pointer to call at environment teardown. \* `[in] arg`: The pointer to pass to `hook` when it gets called. \* `[out] remove\_handle`: Optional handle that refers to the asynchronous cleanup hook. Registers `hook`, which is a function of type [`napi\_async\_cleanup\_hook`][], as a function to be run with the `remove\_handle` and `arg` parameters once the current Node.js environment exits. Unlike [`napi\_add\_env\_cleanup\_hook`][], the hook is allowed to be asynchronous. Otherwise, behavior generally matches that of [`napi\_add\_env\_cleanup\_hook`][]. If `remove\_handle` is not `NULL`, an opaque value will be stored in it that must later be passed to [`napi\_remove\_async\_cleanup\_hook`][], regardless of whether the hook has already been invoked. Typically, that happens when the resource for which this hook was added is being torn down anyway. #### `napi\_remove\_async\_cleanup\_hook` ```c NAPI\_EXTERN napi\_status napi\_remove\_async\_cleanup\_hook( napi\_async\_cleanup\_hook\_handle remove\_handle); ``` \* `[in] remove\_handle`: The handle to an asynchronous cleanup hook that was created with [`napi\_add\_async\_cleanup\_hook`][]. Unregisters the cleanup hook corresponding to `remove\_handle`. This will prevent the hook from being executed, unless it has already started executing. This must be called on any `napi\_async\_cleanup\_hook\_handle` value obtained from [`napi\_add\_async\_cleanup\_hook`][]. ### Finalization on the exit of the Node.js environment The Node.js environment may be torn down at an arbitrary time as soon as possible with JavaScript execution disallowed, like on the request of [`worker.terminate()`][]. When the environment is being torn down, the registered `napi\_finalize` callbacks of JavaScript objects, thread-safe functions and environment instance data are invoked immediately and independently. The invocation of `napi\_finalize` callbacks is scheduled after the manually registered cleanup hooks. In order to ensure a proper order of addon finalization during environment shutdown to avoid use-after-free in the `napi\_finalize` callback, addons should register a cleanup hook with `napi\_add\_env\_cleanup\_hook` and `napi\_add\_async\_cleanup\_hook` to manually release the allocated resource in a proper order. ## Module registration Node-API modules are registered in a manner similar to other modules except that instead of using the `NODE\_MODULE` macro the following is used: ```c NAPI\_MODULE(NODE\_GYP\_MODULE\_NAME, Init) ``` The next difference is the signature for the `Init` method. For a Node-API module it is as follows: ```c napi\_value Init(napi\_env env, napi\_value exports); ``` The return value from `Init` is treated as the `exports` object for the module. The `Init` method is passed an empty object via the `exports` parameter as a convenience. If `Init` returns `NULL`, the parameter passed as `exports` is exported by the module. Node-API modules cannot modify the `module` object but can specify anything as the `exports` property of the module. To add the method `hello` as a function so that it can be called as a method provided by the addon: ```c napi\_value Init(napi\_env env, napi\_value exports) { napi\_status status; napi\_property\_descriptor desc = { "hello", NULL, Method, NULL, NULL, NULL, napi\_writable | napi\_enumerable | napi\_configurable, NULL }; status = napi\_define\_properties(env, exports, 1, &desc); if (status != napi\_ok) return NULL; return exports; } ``` To set a function to be returned by the `require()` for the addon: ```c napi\_value Init(napi\_env env, napi\_value | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.017473580315709114,
0.08123753219842911,
-0.015897236764431,
0.0390983484685421,
0.048996783792972565,
-0.04717493802309036,
0.007722951006144285,
-0.07469363510608673,
-0.008015121333301067,
0.0034978105686604977,
-0.048999108374118805,
0.0059239668771624565,
-0.028910163789987564,
0.0... | 0.12905 |
desc = { "hello", NULL, Method, NULL, NULL, NULL, napi\_writable | napi\_enumerable | napi\_configurable, NULL }; status = napi\_define\_properties(env, exports, 1, &desc); if (status != napi\_ok) return NULL; return exports; } ``` To set a function to be returned by the `require()` for the addon: ```c napi\_value Init(napi\_env env, napi\_value exports) { napi\_value method; napi\_status status; status = napi\_create\_function(env, "exports", NAPI\_AUTO\_LENGTH, Method, NULL, &method); if (status != napi\_ok) return NULL; return method; } ``` To define a class so that new instances can be created (often used with [Object wrap][]): ```c // NOTE: partial example, not all referenced code is included napi\_value Init(napi\_env env, napi\_value exports) { napi\_status status; napi\_property\_descriptor properties[] = { { "value", NULL, NULL, GetValue, SetValue, NULL, napi\_writable | napi\_configurable, NULL }, DECLARE\_NAPI\_METHOD("plusOne", PlusOne), DECLARE\_NAPI\_METHOD("multiply", Multiply), }; napi\_value cons; status = napi\_define\_class(env, "MyObject", New, NULL, 3, properties, &cons); if (status != napi\_ok) return NULL; status = napi\_create\_reference(env, cons, 1, &constructor); if (status != napi\_ok) return NULL; status = napi\_set\_named\_property(env, exports, "MyObject", cons); if (status != napi\_ok) return NULL; return exports; } ``` You can also use the `NAPI\_MODULE\_INIT` macro, which acts as a shorthand for `NAPI\_MODULE` and defining an `Init` function: ```c NAPI\_MODULE\_INIT(/\* napi\_env env, napi\_value exports \*/) { napi\_value answer; napi\_status result; status = napi\_create\_int64(env, 42, &answer); if (status != napi\_ok) return NULL; status = napi\_set\_named\_property(env, exports, "answer", answer); if (status != napi\_ok) return NULL; return exports; } ``` The parameters `env` and `exports` are provided to the body of the `NAPI\_MODULE\_INIT` macro. All Node-API addons are context-aware, meaning they may be loaded multiple times. There are a few design considerations when declaring such a module. The documentation on [context-aware addons][] provides more details. The variables `env` and `exports` will be available inside the function body following the macro invocation. For more details on setting properties on objects, see the section on [Working with JavaScript properties][]. For more details on building addon modules in general, refer to the existing API. ## Working with JavaScript values Node-API exposes a set of APIs to create all types of JavaScript values. Some of these types are documented under [Section language types][] of the [ECMAScript Language Specification][]. Fundamentally, these APIs are used to do one of the following: 1. Create a new JavaScript object 2. Convert from a primitive C type to a Node-API value 3. Convert from Node-API value to a primitive C type 4. Get global instances including `undefined` and `null` Node-API values are represented by the type `napi\_value`. Any Node-API call that requires a JavaScript value takes in a `napi\_value`. In some cases, the API does check the type of the `napi\_value` up-front. However, for better performance, it's better for the caller to make sure that the `napi\_value` in question is of the JavaScript type expected by the API. ### Enum types #### `napi\_key\_collection\_mode` ```c typedef enum { napi\_key\_include\_prototypes, napi\_key\_own\_only } napi\_key\_collection\_mode; ``` Describes the `Keys/Properties` filter enums: `napi\_key\_collection\_mode` limits the range of collected properties. `napi\_key\_own\_only` limits the collected properties to the given object only. `napi\_key\_include\_prototypes` will include all keys of the objects's prototype chain as well. #### `napi\_key\_filter` ```c typedef enum { napi\_key\_all\_properties = 0, napi\_key\_writable = 1, napi\_key\_enumerable = 1 << 1, napi\_key\_configurable = 1 << 2, napi\_key\_skip\_strings = 1 << 3, napi\_key\_skip\_symbols = 1 << 4 } napi\_key\_filter; ``` Property filter bit flag. This works with bit operators to build a composite filter. #### `napi\_key\_conversion` ```c typedef enum { napi\_key\_keep\_numbers, napi\_key\_numbers\_to\_strings } napi\_key\_conversion; ``` `napi\_key\_numbers\_to\_strings` will convert integer indexes to strings. `napi\_key\_keep\_numbers` will return numbers for integer indexes. #### `napi\_valuetype` ```c typedef enum { // ES6 types (corresponds to typeof) napi\_undefined, napi\_null, napi\_boolean, napi\_number, | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.05313713476061821,
0.07938093692064285,
-0.12044715136289597,
0.013010083697736263,
-0.08300270885229111,
-0.007940675131976604,
0.06151985377073288,
0.03635898977518082,
-0.10682666301727295,
-0.037615567445755005,
0.04449840262532234,
-0.10012594610452652,
-0.03853336349129677,
-0.015... | 0.185851 |
works with bit operators to build a composite filter. #### `napi\_key\_conversion` ```c typedef enum { napi\_key\_keep\_numbers, napi\_key\_numbers\_to\_strings } napi\_key\_conversion; ``` `napi\_key\_numbers\_to\_strings` will convert integer indexes to strings. `napi\_key\_keep\_numbers` will return numbers for integer indexes. #### `napi\_valuetype` ```c typedef enum { // ES6 types (corresponds to typeof) napi\_undefined, napi\_null, napi\_boolean, napi\_number, napi\_string, napi\_symbol, napi\_object, napi\_function, napi\_external, napi\_bigint, } napi\_valuetype; ``` Describes the type of a `napi\_value`. This generally corresponds to the types described in [Section language types][] of the ECMAScript Language Specification. In addition to types in that section, `napi\_valuetype` can also represent `Function`s and `Object`s with external data. A JavaScript value of type `napi\_external` appears in JavaScript as a plain object such that no properties can be set on it, and no prototype. #### `napi\_typedarray\_type` ```c typedef enum { napi\_int8\_array, napi\_uint8\_array, napi\_uint8\_clamped\_array, napi\_int16\_array, napi\_uint16\_array, napi\_int32\_array, napi\_uint32\_array, napi\_float32\_array, napi\_float64\_array, napi\_bigint64\_array, napi\_biguint64\_array, napi\_float16\_array, } napi\_typedarray\_type; ``` This represents the underlying binary scalar datatype of the `TypedArray`. Elements of this enum correspond to [Section TypedArray objects][] of the [ECMAScript Language Specification][]. ### Object creation functions #### `napi\_create\_array` ```c napi\_status napi\_create\_array(napi\_env env, napi\_value\* result) ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[out] result`: A `napi\_value` representing a JavaScript `Array`. Returns `napi\_ok` if the API succeeded. This API returns a Node-API value corresponding to a JavaScript `Array` type. JavaScript arrays are described in [Section Array objects][] of the ECMAScript Language Specification. #### `napi\_create\_array\_with\_length` ```c napi\_status napi\_create\_array\_with\_length(napi\_env env, size\_t length, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] length`: The initial length of the `Array`. \* `[out] result`: A `napi\_value` representing a JavaScript `Array`. Returns `napi\_ok` if the API succeeded. This API returns a Node-API value corresponding to a JavaScript `Array` type. The `Array`'s length property is set to the passed-in length parameter. However, the underlying buffer is not guaranteed to be pre-allocated by the VM when the array is created. That behavior is left to the underlying VM implementation. If the buffer must be a contiguous block of memory that can be directly read and/or written via C, consider using [`napi\_create\_external\_arraybuffer`][]. JavaScript arrays are described in [Section Array objects][] of the ECMAScript Language Specification. #### `napi\_create\_arraybuffer` ```c napi\_status napi\_create\_arraybuffer(napi\_env env, size\_t byte\_length, void\*\* data, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] length`: The length in bytes of the array buffer to create. \* `[out] data`: Pointer to the underlying byte buffer of the `ArrayBuffer`. `data` can optionally be ignored by passing `NULL`. \* `[out] result`: A `napi\_value` representing a JavaScript `ArrayBuffer`. Returns `napi\_ok` if the API succeeded. This API returns a Node-API value corresponding to a JavaScript `ArrayBuffer`. `ArrayBuffer`s are used to represent fixed-length binary data buffers. They are normally used as a backing-buffer for `TypedArray` objects. The `ArrayBuffer` allocated will have an underlying byte buffer whose size is determined by the `length` parameter that's passed in. The underlying buffer is optionally returned back to the caller in case the caller wants to directly manipulate the buffer. This buffer can only be written to directly from native code. To write to this buffer from JavaScript, a typed array or `DataView` object would need to be created. JavaScript `ArrayBuffer` objects are described in [Section ArrayBuffer objects][] of the ECMAScript Language Specification. #### `napi\_create\_buffer` ```c napi\_status napi\_create\_buffer(napi\_env env, size\_t size, void\*\* data, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] size`: Size in bytes of the underlying buffer. \* `[out] data`: Raw pointer to the underlying buffer. `data` can optionally be ignored by passing `NULL`. | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.03437366709113121,
0.0780986025929451,
-0.033263612538576126,
-0.017972078174352646,
-0.07976804673671722,
-0.007321896497160196,
0.09512454271316528,
0.01063533779233694,
-0.03349880874156952,
-0.07719049602746964,
-0.022785628214478493,
-0.12423248589038849,
0.005834008101373911,
-0.02... | 0.224571 |
`napi\_create\_buffer` ```c napi\_status napi\_create\_buffer(napi\_env env, size\_t size, void\*\* data, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] size`: Size in bytes of the underlying buffer. \* `[out] data`: Raw pointer to the underlying buffer. `data` can optionally be ignored by passing `NULL`. \* `[out] result`: A `napi\_value` representing a `node::Buffer`. Returns `napi\_ok` if the API succeeded. This API allocates a `node::Buffer` object. While this is still a fully-supported data structure, in most cases using a `TypedArray` will suffice. #### `napi\_create\_buffer\_copy` ```c napi\_status napi\_create\_buffer\_copy(napi\_env env, size\_t length, const void\* data, void\*\* result\_data, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] size`: Size in bytes of the input buffer (should be the same as the size of the new buffer). \* `[in] data`: Raw pointer to the underlying buffer to copy from. \* `[out] result\_data`: Pointer to the new `Buffer`'s underlying data buffer. `result\_data` can optionally be ignored by passing `NULL`. \* `[out] result`: A `napi\_value` representing a `node::Buffer`. Returns `napi\_ok` if the API succeeded. 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. #### `napi\_create\_date` ```c napi\_status napi\_create\_date(napi\_env env, double time, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] time`: ECMAScript time value in milliseconds since 01 January, 1970 UTC. \* `[out] result`: A `napi\_value` representing a JavaScript `Date`. Returns `napi\_ok` if the API succeeded. 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 Date objects][] of the ECMAScript Language Specification. #### `napi\_create\_external` ```c napi\_status napi\_create\_external(napi\_env env, void\* data, napi\_finalize finalize\_cb, void\* finalize\_hint, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] data`: Raw pointer to the external data. \* `[in] finalize\_cb`: Optional callback to call when the external value is being collected. [`napi\_finalize`][] provides more details. \* `[in] finalize\_hint`: Optional hint to pass to the finalize callback during collection. \* `[out] result`: A `napi\_value` representing an external value. Returns `napi\_ok` if the API succeeded. This API allocates a JavaScript value with external data attached to it. This is used to pass external data through JavaScript code, so it can be retrieved later by native code using [`napi\_get\_value\_external`][]. The API adds a `napi\_finalize` callback which will be called when the JavaScript object just created has been garbage collected. The created value is not an object, and therefore does not support additional properties. It is considered a distinct value type: calling `napi\_typeof()` with an external value yields `napi\_external`. #### `napi\_create\_external\_arraybuffer` ```c napi\_status napi\_create\_external\_arraybuffer(napi\_env env, void\* external\_data, size\_t byte\_length, napi\_finalize finalize\_cb, void\* finalize\_hint, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] external\_data`: Pointer to the underlying byte buffer of the `ArrayBuffer`. \* `[in] byte\_length`: The length in bytes of the underlying buffer. \* `[in] finalize\_cb`: Optional callback to call when the `ArrayBuffer` is being collected. [`napi\_finalize`][] provides more details. \* `[in] finalize\_hint`: Optional hint to pass to the finalize callback during collection. \* `[out] result`: A `napi\_value` representing a JavaScript `ArrayBuffer`. Returns `napi\_ok` if the API succeeded. \*\*Some runtimes other than Node.js have dropped support for external buffers\*\*. On runtimes other than Node.js this method may return `napi\_no\_external\_buffers\_allowed` to indicate that external buffers are not supported. One such runtime is Electron as described in this issue [electron/issues/35801](https://github.com/electron/electron/issues/35801). In order | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.00028061747434549034,
0.08068951964378357,
-0.06958974897861481,
0.012315364554524422,
-0.08645576238632202,
-0.07337076216936111,
0.04217187687754631,
-0.016799958422780037,
-0.008238164708018303,
-0.034510958939790726,
-0.019624868407845497,
-0.05490082502365112,
-0.011492040939629078,
... | 0.178885 |
JavaScript `ArrayBuffer`. Returns `napi\_ok` if the API succeeded. \*\*Some runtimes other than Node.js have dropped support for external buffers\*\*. On runtimes other than Node.js this method may return `napi\_no\_external\_buffers\_allowed` to indicate that external buffers are not supported. One such runtime is Electron as described in this issue [electron/issues/35801](https://github.com/electron/electron/issues/35801). In order to maintain broadest compatibility with all runtimes you may define `NODE\_API\_NO\_EXTERNAL\_BUFFERS\_ALLOWED` in your addon before includes for the node-api headers. Doing so will hide the 2 functions that create external buffers. This will ensure a compilation error occurs if you accidentally use one of these methods. This API returns a Node-API value corresponding to a JavaScript `ArrayBuffer`. The underlying byte buffer of the `ArrayBuffer` is externally allocated and managed. The caller must ensure that the byte buffer remains valid until the finalize callback is called. The API adds a `napi\_finalize` callback which will be called when the JavaScript object just created has been garbage collected. JavaScript `ArrayBuffer`s are described in [Section ArrayBuffer objects][] of the ECMAScript Language Specification. #### `napi\_create\_external\_buffer` ```c napi\_status napi\_create\_external\_buffer(napi\_env env, size\_t length, void\* data, napi\_finalize finalize\_cb, void\* finalize\_hint, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] length`: Size in bytes of the input buffer (should be the same as the size of the new buffer). \* `[in] data`: Raw pointer to the underlying buffer to expose to JavaScript. \* `[in] finalize\_cb`: Optional callback to call when the `ArrayBuffer` is being collected. [`napi\_finalize`][] provides more details. \* `[in] finalize\_hint`: Optional hint to pass to the finalize callback during collection. \* `[out] result`: A `napi\_value` representing a `node::Buffer`. Returns `napi\_ok` if the API succeeded. \*\*Some runtimes other than Node.js have dropped support for external buffers\*\*. On runtimes other than Node.js this method may return `napi\_no\_external\_buffers\_allowed` to indicate that external buffers are not supported. One such runtime is Electron as described in this issue [electron/issues/35801](https://github.com/electron/electron/issues/35801). In order to maintain broadest compatibility with all runtimes you may define `NODE\_API\_NO\_EXTERNAL\_BUFFERS\_ALLOWED` in your addon before includes for the node-api headers. Doing so will hide the 2 functions that create external buffers. This will ensure a compilation error occurs if you accidentally use one of these methods. 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. The API adds a `napi\_finalize` callback which will be called when the JavaScript object just created has been garbage collected. For Node.js >=4 `Buffers` are `Uint8Array`s. #### `napi\_create\_object` ```c napi\_status napi\_create\_object(napi\_env env, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: A `napi\_value` representing a JavaScript `Object`. Returns `napi\_ok` if the API succeeded. This API allocates a default JavaScript `Object`. It is the equivalent of doing `new Object()` in JavaScript. The JavaScript `Object` type is described in [Section object type][] of the ECMAScript Language Specification. #### `node\_api\_create\_object\_with\_properties` > Stability: 1 - Experimental ```cpp napi\_status node\_api\_create\_object\_with\_properties(napi\_env env, napi\_value prototype\_or\_null, const napi\_value\* property\_names, const napi\_value\* property\_values, size\_t property\_count, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] prototype\_or\_null`: The prototype object for the new object. Can be a `napi\_value` representing a JavaScript object to use as the prototype, a `napi\_value` representing JavaScript `null`, or a `nullptr` that will be converted to `null`. \* `[in] property\_names`: Array of `napi\_value` representing the property names. \* `[in] property\_values`: Array of `napi\_value` representing the property values. \* `[in] property\_count`: Number of properties in the arrays. \* `[out] result`: A `napi\_value` representing a JavaScript `Object`. Returns `napi\_ok` | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.06857969611883163,
0.053608156740665436,
-0.005678572226315737,
0.04512307792901993,
-0.026993514969944954,
-0.05799074470996857,
-0.04350646212697029,
0.0364583320915699,
-0.02899392880499363,
-0.06743822991847992,
-0.04113342985510826,
-0.05234713479876518,
-0.06556305289268494,
0.008... | 0.090241 |
`null`, or a `nullptr` that will be converted to `null`. \* `[in] property\_names`: Array of `napi\_value` representing the property names. \* `[in] property\_values`: Array of `napi\_value` representing the property values. \* `[in] property\_count`: Number of properties in the arrays. \* `[out] result`: A `napi\_value` representing a JavaScript `Object`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `Object` with the specified prototype and properties. This is more efficient than calling `napi\_create\_object` followed by multiple `napi\_set\_property` calls, as it can create the object with all properties atomically, avoiding potential V8 map transitions. The arrays `property\_names` and `property\_values` must have the same length specified by `property\_count`. The properties are added to the object in the order they appear in the arrays. #### `napi\_create\_symbol` ```c napi\_status napi\_create\_symbol(napi\_env env, napi\_value description, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] description`: Optional `napi\_value` which refers to a JavaScript `string` to be set as the description for the symbol. \* `[out] result`: A `napi\_value` representing a JavaScript `symbol`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `symbol` value from a UTF8-encoded C string. The JavaScript `symbol` type is described in [Section symbol type][] of the ECMAScript Language Specification. #### `node\_api\_symbol\_for` ```c napi\_status node\_api\_symbol\_for(napi\_env env, const char\* utf8description, size\_t length, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] utf8description`: UTF-8 C string representing the text to be used as the description for the symbol. \* `[in] length`: The length of the description string in bytes, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[out] result`: A `napi\_value` representing a JavaScript `symbol`. Returns `napi\_ok` if the API succeeded. This API searches in the global registry for an existing symbol with the given description. If the symbol already exists it will be returned, otherwise a new symbol will be created in the registry. The JavaScript `symbol` type is described in [Section symbol type][] of the ECMAScript Language Specification. #### `napi\_create\_typedarray` ```c napi\_status napi\_create\_typedarray(napi\_env env, napi\_typedarray\_type type, size\_t length, napi\_value arraybuffer, size\_t byte\_offset, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] type`: Scalar datatype of the elements within the `TypedArray`. \* `[in] length`: Number of elements in the `TypedArray`. \* `[in] arraybuffer`: `ArrayBuffer` underlying the typed array. \* `[in] byte\_offset`: The byte offset within the `ArrayBuffer` from which to start projecting the `TypedArray`. \* `[out] result`: A `napi\_value` representing a JavaScript `TypedArray`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `TypedArray` object over an existing `ArrayBuffer`. `TypedArray` objects provide an array-like view over an underlying data buffer where each element has the same underlying binary scalar datatype. It's required that `(length \* size\_of\_element) + byte\_offset` should be <= the size in bytes of the array passed in. If not, a `RangeError` exception is raised. JavaScript `TypedArray` objects are described in [Section TypedArray objects][] of the ECMAScript Language Specification. #### `node\_api\_create\_buffer\_from\_arraybuffer` ```c napi\_status NAPI\_CDECL node\_api\_create\_buffer\_from\_arraybuffer(napi\_env env, napi\_value arraybuffer, size\_t byte\_offset, size\_t byte\_length, napi\_value\* result) ``` \* \*\*`[in] env`\*\*: The environment that the API is invoked under. \* \*\*`[in] arraybuffer`\*\*: The `ArrayBuffer` from which the buffer will be created. \* \*\*`[in] byte\_offset`\*\*: The byte offset within the `ArrayBuffer` from which to start creating the buffer. \* \*\*`[in] byte\_length`\*\*: The length in bytes of the buffer to be created from the `ArrayBuffer`. \* \*\*`[out] result`\*\*: A `napi\_value` representing the created JavaScript `Buffer` object. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `Buffer` object from an existing `ArrayBuffer`. The `Buffer` object is a Node.js-specific class that provides a way to | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.05822683125734329,
0.0729823112487793,
-0.022403964772820473,
0.043743494898080826,
-0.11427272856235504,
-0.01214747503399849,
0.02487947605550289,
-0.035073913633823395,
0.017304738983511925,
-0.08985202014446259,
-0.02190718613564968,
-0.10099226981401443,
0.0066045052371919155,
-0.0... | 0.146383 |
bytes of the buffer to be created from the `ArrayBuffer`. \* \*\*`[out] result`\*\*: A `napi\_value` representing the created JavaScript `Buffer` object. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `Buffer` object from an existing `ArrayBuffer`. The `Buffer` object is a Node.js-specific class that provides a way to work with binary data directly in JavaScript. The byte range `[byte\_offset, byte\_offset + byte\_length)` must be within the bounds of the `ArrayBuffer`. If `byte\_offset + byte\_length` exceeds the size of the `ArrayBuffer`, a `RangeError` exception is raised. #### `napi\_create\_dataview` ```c napi\_status napi\_create\_dataview(napi\_env env, size\_t byte\_length, napi\_value arraybuffer, size\_t byte\_offset, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] length`: Number of elements in the `DataView`. \* `[in] arraybuffer`: `ArrayBuffer` or `SharedArrayBuffer` underlying the `DataView`. \* `[in] byte\_offset`: The byte offset within the `ArrayBuffer` from which to start projecting the `DataView`. \* `[out] result`: A `napi\_value` representing a JavaScript `DataView`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `DataView` object over an existing `ArrayBuffer` or `SharedArrayBuffer`. `DataView` objects provide an array-like view over an underlying data buffer, but one which allows items of different size and type in the `ArrayBuffer` or `SharedArrayBuffer`. It is required that `byte\_length + byte\_offset` is less than or equal to the size in bytes of the array passed in. If not, a `RangeError` exception is raised. JavaScript `DataView` objects are described in [Section DataView objects][] of the ECMAScript Language Specification. ### Functions to convert from C types to Node-API #### `napi\_create\_int32` ```c napi\_status napi\_create\_int32(napi\_env env, int32\_t value, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: Integer value to be represented in JavaScript. \* `[out] result`: A `napi\_value` representing a JavaScript `number`. Returns `napi\_ok` if the API succeeded. This API is used to convert from the C `int32\_t` type to the JavaScript `number` type. The JavaScript `number` type is described in [Section number type][] of the ECMAScript Language Specification. #### `napi\_create\_uint32` ```c napi\_status napi\_create\_uint32(napi\_env env, uint32\_t value, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: Unsigned integer value to be represented in JavaScript. \* `[out] result`: A `napi\_value` representing a JavaScript `number`. Returns `napi\_ok` if the API succeeded. This API is used to convert from the C `uint32\_t` type to the JavaScript `number` type. The JavaScript `number` type is described in [Section number type][] of the ECMAScript Language Specification. #### `napi\_create\_int64` ```c napi\_status napi\_create\_int64(napi\_env env, int64\_t value, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: Integer value to be represented in JavaScript. \* `[out] result`: A `napi\_value` representing a JavaScript `number`. Returns `napi\_ok` if the API succeeded. This API is used to convert from the C `int64\_t` type to the JavaScript `number` type. The JavaScript `number` type is described in [Section number type][] of the ECMAScript Language Specification. Note the complete range of `int64\_t` cannot be represented with full precision in JavaScript. Integer values outside the range of [`Number.MIN\_SAFE\_INTEGER`][] `-(2\*\*53 - 1)` - [`Number.MAX\_SAFE\_INTEGER`][] `(2\*\*53 - 1)` will lose precision. #### `napi\_create\_double` ```c napi\_status napi\_create\_double(napi\_env env, double value, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: Double-precision value to be represented in JavaScript. \* `[out] result`: A `napi\_value` representing a JavaScript `number`. Returns `napi\_ok` if the API succeeded. This API is used to convert from the C `double` type to the JavaScript `number` type. The JavaScript `number` type is described in [Section number type][] of the ECMAScript Language Specification. #### `napi\_create\_bigint\_int64` | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.0036726491525769234,
0.015447014942765236,
-0.0238462146371603,
-0.03942059725522995,
-0.10823062807321548,
-0.05245189741253853,
0.04281865060329437,
0.04444229602813721,
-0.03622312471270561,
-0.08194499462842941,
-0.05459309741854668,
-0.02275250479578972,
0.013429422862827778,
-0.047... | 0.098651 |
in JavaScript. \* `[out] result`: A `napi\_value` representing a JavaScript `number`. Returns `napi\_ok` if the API succeeded. This API is used to convert from the C `double` type to the JavaScript `number` type. The JavaScript `number` type is described in [Section number type][] of the ECMAScript Language Specification. #### `napi\_create\_bigint\_int64` ```c napi\_status napi\_create\_bigint\_int64(napi\_env env, int64\_t value, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: Integer value to be represented in JavaScript. \* `[out] result`: A `napi\_value` representing a JavaScript `BigInt`. Returns `napi\_ok` if the API succeeded. This API converts the C `int64\_t` type to the JavaScript `BigInt` type. #### `napi\_create\_bigint\_uint64` ```c napi\_status napi\_create\_bigint\_uint64(napi\_env env, uint64\_t value, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: Unsigned integer value to be represented in JavaScript. \* `[out] result`: A `napi\_value` representing a JavaScript `BigInt`. Returns `napi\_ok` if the API succeeded. This API converts the C `uint64\_t` type to the JavaScript `BigInt` type. #### `napi\_create\_bigint\_words` ```c napi\_status napi\_create\_bigint\_words(napi\_env env, int sign\_bit, size\_t word\_count, const uint64\_t\* words, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] sign\_bit`: Determines if the resulting `BigInt` will be positive or negative. \* `[in] word\_count`: The length of the `words` array. \* `[in] words`: An array of `uint64\_t` little-endian 64-bit words. \* `[out] result`: A `napi\_value` representing a JavaScript `BigInt`. Returns `napi\_ok` if the API succeeded. This API converts an array of unsigned 64-bit words into a single `BigInt` value. The resulting `BigInt` is calculated as: (–1)`sign\_bit` (`words[0]` × (264)0 + `words[1]` × (264)1 + …) #### `napi\_create\_string\_latin1` ```c napi\_status napi\_create\_string\_latin1(napi\_env env, const char\* str, size\_t length, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] str`: Character buffer representing an ISO-8859-1-encoded string. \* `[in] length`: The length of the string in bytes, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[out] result`: A `napi\_value` representing a JavaScript `string`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `string` value from an ISO-8859-1-encoded C string. The native string is copied. The JavaScript `string` type is described in [Section string type][] of the ECMAScript Language Specification. #### `node\_api\_create\_external\_string\_latin1` ```c napi\_status node\_api\_create\_external\_string\_latin1(napi\_env env, char\* str, size\_t length, napi\_finalize finalize\_callback, void\* finalize\_hint, napi\_value\* result, bool\* copied); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] str`: Character buffer representing an ISO-8859-1-encoded string. \* `[in] length`: The length of the string in bytes, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[in] finalize\_callback`: The function to call when the string is being collected. The function will be called with the following parameters: \* `[in] env`: The environment in which the add-on is running. This value may be null if the string is being collected as part of the termination of the worker or the main Node.js instance. \* `[in] data`: This is the value `str` as a `void\*` pointer. \* `[in] finalize\_hint`: This is the value `finalize\_hint` that was given to the API. [`napi\_finalize`][] provides more details. This parameter is optional. Passing a null value means that the add-on doesn't need to be notified when the corresponding JavaScript string is collected. \* `[in] finalize\_hint`: Optional hint to pass to the finalize callback during collection. \* `[out] result`: A `napi\_value` representing a JavaScript `string`. \* `[out] copied`: Whether the string was copied. If it was, the finalizer will already have been invoked to destroy `str`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `string` value from an ISO-8859-1-encoded C string. The native string may not | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.03334081918001175,
0.09580030292272568,
0.018031742423772812,
0.009693118743598461,
-0.03239418566226959,
-0.01380634680390358,
0.0072357612662017345,
0.08157986402511597,
0.027846235781908035,
-0.09153448790311813,
-0.06764862686395645,
-0.031143654137849808,
0.002105267019942403,
0.02... | 0.211503 |
A `napi\_value` representing a JavaScript `string`. \* `[out] copied`: Whether the string was copied. If it was, the finalizer will already have been invoked to destroy `str`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `string` value from an ISO-8859-1-encoded C string. The native string may not be copied and must thus exist for the entire life cycle of the JavaScript value. The JavaScript `string` type is described in [Section string type][] of the ECMAScript Language Specification. #### `napi\_create\_string\_utf16` ```c napi\_status napi\_create\_string\_utf16(napi\_env env, const char16\_t\* str, size\_t length, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] str`: Character buffer representing a UTF16-LE-encoded string. \* `[in] length`: The length of the string in two-byte code units, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[out] result`: A `napi\_value` representing a JavaScript `string`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `string` value from a UTF16-LE-encoded C string. The native string is copied. The JavaScript `string` type is described in [Section string type][] of the ECMAScript Language Specification. #### `node\_api\_create\_external\_string\_utf16` ```c napi\_status node\_api\_create\_external\_string\_utf16(napi\_env env, char16\_t\* str, size\_t length, napi\_finalize finalize\_callback, void\* finalize\_hint, napi\_value\* result, bool\* copied); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] str`: Character buffer representing a UTF16-LE-encoded string. \* `[in] length`: The length of the string in two-byte code units, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[in] finalize\_callback`: The function to call when the string is being collected. The function will be called with the following parameters: \* `[in] env`: The environment in which the add-on is running. This value may be null if the string is being collected as part of the termination of the worker or the main Node.js instance. \* `[in] data`: This is the value `str` as a `void\*` pointer. \* `[in] finalize\_hint`: This is the value `finalize\_hint` that was given to the API. [`napi\_finalize`][] provides more details. This parameter is optional. Passing a null value means that the add-on doesn't need to be notified when the corresponding JavaScript string is collected. \* `[in] finalize\_hint`: Optional hint to pass to the finalize callback during collection. \* `[out] result`: A `napi\_value` representing a JavaScript `string`. \* `[out] copied`: Whether the string was copied. If it was, the finalizer will already have been invoked to destroy `str`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `string` value from a UTF16-LE-encoded C string. The native string may not be copied and must thus exist for the entire life cycle of the JavaScript value. The JavaScript `string` type is described in [Section string type][] of the ECMAScript Language Specification. #### `napi\_create\_string\_utf8` ```c napi\_status napi\_create\_string\_utf8(napi\_env env, const char\* str, size\_t length, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] str`: Character buffer representing a UTF8-encoded string. \* `[in] length`: The length of the string in bytes, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[out] result`: A `napi\_value` representing a JavaScript `string`. Returns `napi\_ok` if the API succeeded. This API creates a JavaScript `string` value from a UTF8-encoded C string. The native string is copied. The JavaScript `string` type is described in [Section string type][] of the ECMAScript Language Specification. ### Functions to create optimized property keys Many JavaScript engines including V8 use internalized strings as keys to set and get property values. They typically use a hash table to create and lookup such strings. While it adds some cost per key creation, it improves the performance after that by enabling comparison of string pointers instead of the whole strings. | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.03937707468867302,
0.1031414270401001,
-0.0057846191339194775,
-0.025288676843047142,
-0.07762307673692703,
-0.033980660140514374,
0.016597889363765717,
0.05569072812795639,
0.015508178621530533,
-0.11245749890804291,
-0.016621548682451248,
-0.05667810142040253,
-0.0242831502109766,
0.0... | 0.194537 |
including V8 use internalized strings as keys to set and get property values. They typically use a hash table to create and lookup such strings. While it adds some cost per key creation, it improves the performance after that by enabling comparison of string pointers instead of the whole strings. If a new JavaScript string is intended to be used as a property key, then for some JavaScript engines it will be more efficient to use the functions in this section. Otherwise, use the `napi\_create\_string\_utf8` or `node\_api\_create\_external\_string\_utf8` series functions as there may be additional overhead in creating/storing strings with the property key creation methods. #### `node\_api\_create\_property\_key\_latin1` ```c napi\_status NAPI\_CDECL node\_api\_create\_property\_key\_latin1(napi\_env env, const char\* str, size\_t length, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] str`: Character buffer representing an ISO-8859-1-encoded string. \* `[in] length`: The length of the string in bytes, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[out] result`: A `napi\_value` representing an optimized JavaScript `string` to be used as a property key for objects. Returns `napi\_ok` if the API succeeded. This API creates an optimized JavaScript `string` value from an ISO-8859-1-encoded C string to be used as a property key for objects. The native string is copied. In contrast with `napi\_create\_string\_latin1`, subsequent calls to this function with the same `str` pointer may benefit from a speedup in the creation of the requested `napi\_value`, depending on the engine. The JavaScript `string` type is described in [Section string type][] of the ECMAScript Language Specification. #### `node\_api\_create\_property\_key\_utf16` ```c napi\_status NAPI\_CDECL node\_api\_create\_property\_key\_utf16(napi\_env env, const char16\_t\* str, size\_t length, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] str`: Character buffer representing a UTF16-LE-encoded string. \* `[in] length`: The length of the string in two-byte code units, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[out] result`: A `napi\_value` representing an optimized JavaScript `string` to be used as a property key for objects. Returns `napi\_ok` if the API succeeded. This API creates an optimized JavaScript `string` value from a UTF16-LE-encoded C string to be used as a property key for objects. The native string is copied. The JavaScript `string` type is described in [Section string type][] of the ECMAScript Language Specification. #### `node\_api\_create\_property\_key\_utf8` ```c napi\_status NAPI\_CDECL node\_api\_create\_property\_key\_utf8(napi\_env env, const char\* str, size\_t length, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] str`: Character buffer representing a UTF8-encoded string. \* `[in] length`: The length of the string in two-byte code units, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[out] result`: A `napi\_value` representing an optimized JavaScript `string` to be used as a property key for objects. Returns `napi\_ok` if the API succeeded. This API creates an optimized JavaScript `string` value from a UTF8-encoded C string to be used as a property key for objects. The native string is copied. The JavaScript `string` type is described in [Section string type][] of the ECMAScript Language Specification. ### Functions to convert from Node-API to C types #### `napi\_get\_array\_length` ```c napi\_status napi\_get\_array\_length(napi\_env env, napi\_value value, uint32\_t\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing the JavaScript `Array` whose length is being queried. \* `[out] result`: `uint32` representing length of the array. Returns `napi\_ok` if the API succeeded. This API returns the length of an array. `Array` length is described in [Section Array instance length][] of the ECMAScript Language Specification. #### `napi\_get\_arraybuffer\_info` ```c napi\_status napi\_get\_arraybuffer\_info(napi\_env env, napi\_value arraybuffer, void\*\* data, size\_t\* byte\_length) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] arraybuffer`: | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.03558674082159996,
0.04913724586367607,
-0.000819711945950985,
0.005025568418204784,
-0.07715753465890884,
-0.003097074804827571,
-0.0029054624028503895,
0.05372912436723709,
0.021623658016324043,
-0.08701271563768387,
-0.016110528260469437,
-0.03363949805498123,
-0.0052783372811973095,
... | 0.069009 |
succeeded. This API returns the length of an array. `Array` length is described in [Section Array instance length][] of the ECMAScript Language Specification. #### `napi\_get\_arraybuffer\_info` ```c napi\_status napi\_get\_arraybuffer\_info(napi\_env env, napi\_value arraybuffer, void\*\* data, size\_t\* byte\_length) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] arraybuffer`: `napi\_value` representing the `ArrayBuffer` or `SharedArrayBuffer` being queried. \* `[out] data`: The underlying data buffer of the `ArrayBuffer` or `SharedArrayBuffer` is `0`, this may be `NULL` or any other pointer value. \* `[out] byte\_length`: Length in bytes of the underlying data buffer. Returns `napi\_ok` if the API succeeded. This API is used to retrieve the underlying data buffer of an `ArrayBuffer` or `SharedArrayBuffer` and its length. \_WARNING\_: Use caution while using this API. The lifetime of the underlying data buffer is managed by the `ArrayBuffer` or `SharedArrayBuffer` even after it's returned. A possible safe way to use this API is in conjunction with [`napi\_create\_reference`][], which can be used to guarantee control over the lifetime of the `ArrayBuffer` or `SharedArrayBuffer`. It's also safe to use the returned data buffer within the same callback as long as there are no calls to other APIs that might trigger a GC. #### `napi\_get\_buffer\_info` ```c napi\_status napi\_get\_buffer\_info(napi\_env env, napi\_value value, void\*\* data, size\_t\* length) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing the `node::Buffer` or `Uint8Array` being queried. \* `[out] data`: The underlying data buffer of the `node::Buffer` or `Uint8Array`. If length is `0`, this may be `NULL` or any other pointer value. \* `[out] length`: Length in bytes of the underlying data buffer. Returns `napi\_ok` if the API succeeded. This method returns the identical `data` and `byte\_length` as [`napi\_get\_typedarray\_info`][]. And `napi\_get\_typedarray\_info` accepts a `node::Buffer` (a Uint8Array) as the value too. This API is used to retrieve the underlying data buffer of a `node::Buffer` and its length. \_Warning\_: Use caution while using this API since the underlying data buffer's lifetime is not guaranteed if it's managed by the VM. #### `napi\_get\_prototype` ```c napi\_status napi\_get\_prototype(napi\_env env, napi\_value object, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] object`: `napi\_value` representing JavaScript `Object` whose prototype to return. This returns the equivalent of `Object.getPrototypeOf` (which is not the same as the function's `prototype` property). \* `[out] result`: `napi\_value` representing prototype of the given object. Returns `napi\_ok` if the API succeeded. #### `napi\_get\_typedarray\_info` ```c napi\_status napi\_get\_typedarray\_info(napi\_env env, napi\_value typedarray, napi\_typedarray\_type\* type, size\_t\* length, void\*\* data, napi\_value\* arraybuffer, size\_t\* byte\_offset) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] typedarray`: `napi\_value` representing the `TypedArray` whose properties to query. \* `[out] type`: Scalar datatype of the elements within the `TypedArray`. \* `[out] length`: The number of elements in the `TypedArray`. \* `[out] data`: The data buffer underlying the `TypedArray` adjusted by the `byte\_offset` value so that it points to the first element in the `TypedArray`. If the length of the array is `0`, this may be `NULL` or any other pointer value. \* `[out] arraybuffer`: The `ArrayBuffer` underlying the `TypedArray`. \* `[out] byte\_offset`: The byte offset within the underlying native array at which the first element of the arrays is located. The value for the data parameter has already been adjusted so that data points to the first element in the array. Therefore, the first byte of the native array would be at `data - byte\_offset`. Returns `napi\_ok` if the API succeeded. This API returns various properties of a typed array. Any of the out parameters may be `NULL` if that property is unneeded. \_Warning\_: Use caution while using this | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.03906982019543648,
0.10601309686899185,
-0.052140012383461,
-0.010414277203381062,
-0.046139538288116455,
-0.031830161809921265,
0.013831579126417637,
0.044853080064058304,
-0.03187539055943489,
-0.09954682737588882,
-0.06638089567422867,
-0.05129513144493103,
-0.02021024189889431,
-0.01... | 0.191051 |
the array. Therefore, the first byte of the native array would be at `data - byte\_offset`. Returns `napi\_ok` if the API succeeded. This API returns various properties of a typed array. Any of the out parameters may be `NULL` if that property is unneeded. \_Warning\_: Use caution while using this API since the underlying data buffer is managed by the VM. #### `napi\_get\_dataview\_info` ```c napi\_status napi\_get\_dataview\_info(napi\_env env, napi\_value dataview, size\_t\* byte\_length, void\*\* data, napi\_value\* arraybuffer, size\_t\* byte\_offset) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] dataview`: `napi\_value` representing the `DataView` whose properties to query. \* `[out] byte\_length`: Number of bytes in the `DataView`. \* `[out] data`: The data buffer underlying the `DataView`. If byte\\_length is `0`, this may be `NULL` or any other pointer value. \* `[out] arraybuffer`: `ArrayBuffer` underlying the `DataView`. \* `[out] byte\_offset`: The byte offset within the data buffer from which to start projecting the `DataView`. Returns `napi\_ok` if the API succeeded. Any of the out parameters may be `NULL` if that property is unneeded. This API returns various properties of a `DataView`. #### `napi\_get\_date\_value` ```c napi\_status napi\_get\_date\_value(napi\_env env, napi\_value value, double\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing a JavaScript `Date`. \* `[out] result`: Time value as a `double` represented as milliseconds since midnight at the beginning of 01 January, 1970 UTC. This API does not observe leap seconds; they are ignored, as ECMAScript aligns with POSIX time specification. Returns `napi\_ok` if the API succeeded. If a non-date `napi\_value` is passed in it returns `napi\_date\_expected`. This API returns the C double primitive of time value for the given JavaScript `Date`. #### `napi\_get\_value\_bool` ```c napi\_status napi\_get\_value\_bool(napi\_env env, napi\_value value, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript `Boolean`. \* `[out] result`: C boolean primitive equivalent of the given JavaScript `Boolean`. Returns `napi\_ok` if the API succeeded. If a non-boolean `napi\_value` is passed in it returns `napi\_boolean\_expected`. This API returns the C boolean primitive equivalent of the given JavaScript `Boolean`. #### `napi\_get\_value\_double` ```c napi\_status napi\_get\_value\_double(napi\_env env, napi\_value value, double\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript `number`. \* `[out] result`: C double primitive equivalent of the given JavaScript `number`. Returns `napi\_ok` if the API succeeded. If a non-number `napi\_value` is passed in it returns `napi\_number\_expected`. This API returns the C double primitive equivalent of the given JavaScript `number`. #### `napi\_get\_value\_bigint\_int64` ```c napi\_status napi\_get\_value\_bigint\_int64(napi\_env env, napi\_value value, int64\_t\* result, bool\* lossless); ``` \* `[in] env`: The environment that the API is invoked under \* `[in] value`: `napi\_value` representing JavaScript `BigInt`. \* `[out] result`: C `int64\_t` primitive equivalent of the given JavaScript `BigInt`. \* `[out] lossless`: Indicates whether the `BigInt` value was converted losslessly. Returns `napi\_ok` if the API succeeded. If a non-`BigInt` is passed in it returns `napi\_bigint\_expected`. This API returns the C `int64\_t` primitive equivalent of the given JavaScript `BigInt`. If needed it will truncate the value, setting `lossless` to `false`. #### `napi\_get\_value\_bigint\_uint64` ```c napi\_status napi\_get\_value\_bigint\_uint64(napi\_env env, napi\_value value, uint64\_t\* result, bool\* lossless); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript `BigInt`. \* `[out] result`: C `uint64\_t` primitive equivalent of the given JavaScript `BigInt`. \* `[out] lossless`: Indicates whether the `BigInt` value was converted losslessly. Returns `napi\_ok` if the API succeeded. If a non-`BigInt` is passed in it returns `napi\_bigint\_expected`. This API returns the C `uint64\_t` primitive equivalent of the given JavaScript `BigInt`. If needed it will | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.06106945127248764,
0.06190337613224983,
-0.06401555240154266,
-0.03760169446468353,
-0.09497170150279999,
-0.052739351987838745,
0.08574279397726059,
0.010429403744637966,
-0.03542178124189377,
-0.0606810562312603,
-0.009810819290578365,
-0.08304805308580399,
-0.005180777050554752,
-0.06... | 0.1275 |
primitive equivalent of the given JavaScript `BigInt`. \* `[out] lossless`: Indicates whether the `BigInt` value was converted losslessly. Returns `napi\_ok` if the API succeeded. If a non-`BigInt` is passed in it returns `napi\_bigint\_expected`. This API returns the C `uint64\_t` primitive equivalent of the given JavaScript `BigInt`. If needed it will truncate the value, setting `lossless` to `false`. #### `napi\_get\_value\_bigint\_words` ```c napi\_status napi\_get\_value\_bigint\_words(napi\_env env, napi\_value value, int\* sign\_bit, size\_t\* word\_count, uint64\_t\* words); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript `BigInt`. \* `[out] sign\_bit`: Integer representing if the JavaScript `BigInt` is positive or negative. \* `[in/out] word\_count`: Must be initialized to the length of the `words` array. Upon return, it will be set to the actual number of words that would be needed to store this `BigInt`. \* `[out] words`: Pointer to a pre-allocated 64-bit word array. Returns `napi\_ok` if the API succeeded. This API converts a single `BigInt` value into a sign bit, 64-bit little-endian array, and the number of elements in the array. `sign\_bit` and `words` may be both set to `NULL`, in order to get only `word\_count`. #### `napi\_get\_value\_external` ```c napi\_status napi\_get\_value\_external(napi\_env env, napi\_value value, void\*\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript external value. \* `[out] result`: Pointer to the data wrapped by the JavaScript external value. Returns `napi\_ok` if the API succeeded. If a non-external `napi\_value` is passed in it returns `napi\_invalid\_arg`. This API retrieves the external data pointer that was previously passed to `napi\_create\_external()`. #### `napi\_get\_value\_int32` ```c napi\_status napi\_get\_value\_int32(napi\_env env, napi\_value value, int32\_t\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript `number`. \* `[out] result`: C `int32` primitive equivalent of the given JavaScript `number`. Returns `napi\_ok` if the API succeeded. If a non-number `napi\_value` is passed in `napi\_number\_expected`. This API returns the C `int32` primitive equivalent of the given JavaScript `number`. If the number exceeds the range of the 32 bit integer, then the result is truncated to the equivalent of the bottom 32 bits. This can result in a large positive number becoming a negative number if the value is > 231 - 1. Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the result to zero. #### `napi\_get\_value\_int64` ```c napi\_status napi\_get\_value\_int64(napi\_env env, napi\_value value, int64\_t\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript `number`. \* `[out] result`: C `int64` primitive equivalent of the given JavaScript `number`. Returns `napi\_ok` if the API succeeded. If a non-number `napi\_value` is passed in it returns `napi\_number\_expected`. This API returns the C `int64` primitive equivalent of the given JavaScript `number`. `number` values outside the range of [`Number.MIN\_SAFE\_INTEGER`][] `-(2\*\*53 - 1)` - [`Number.MAX\_SAFE\_INTEGER`][] `(2\*\*53 - 1)` will lose precision. Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the result to zero. #### `napi\_get\_value\_string\_latin1` ```c napi\_status napi\_get\_value\_string\_latin1(napi\_env env, napi\_value value, char\* buf, size\_t bufsize, size\_t\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript string. \* `[in] buf`: Buffer to write the ISO-8859-1-encoded string into. If `NULL` is passed in, the length of the string in bytes and excluding the null terminator is returned in `result`. \* `[in] bufsize`: Size of the destination buffer. When this value is insufficient, the returned string is truncated and null-terminated. If this value is zero, then the string is not returned and no changes are done to the buffer. \* `[out] result`: Number of bytes copied into the buffer, excluding the | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.017600003629922867,
0.129165381193161,
-0.0006582419155165553,
0.023607909679412842,
-0.041998911648988724,
-0.09194520115852356,
0.023875156417489052,
0.05318713188171387,
-0.015270222909748554,
-0.040041450411081314,
-0.0528712272644043,
-0.014299068599939346,
0.0067464327439665794,
-0... | 0.178908 |
`[in] bufsize`: Size of the destination buffer. When this value is insufficient, the returned string is truncated and null-terminated. If this value is zero, then the string is not returned and no changes are done to the buffer. \* `[out] result`: Number of bytes copied into the buffer, excluding the null terminator. Returns `napi\_ok` if the API succeeded. If a non-`string` `napi\_value` is passed in it returns `napi\_string\_expected`. This API returns the ISO-8859-1-encoded string corresponding the value passed in. #### `napi\_get\_value\_string\_utf8` ```c napi\_status napi\_get\_value\_string\_utf8(napi\_env env, napi\_value value, char\* buf, size\_t bufsize, size\_t\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript string. \* `[in] buf`: Buffer to write the UTF8-encoded string into. If `NULL` is passed in, the length of the string in bytes and excluding the null terminator is returned in `result`. \* `[in] bufsize`: Size of the destination buffer. When this value is insufficient, the returned string is truncated and null-terminated. If this value is zero, then the string is not returned and no changes are done to the buffer. \* `[out] result`: Number of bytes copied into the buffer, excluding the null terminator. Returns `napi\_ok` if the API succeeded. If a non-`string` `napi\_value` is passed in it returns `napi\_string\_expected`. This API returns the UTF8-encoded string corresponding the value passed in. #### `napi\_get\_value\_string\_utf16` ```c napi\_status napi\_get\_value\_string\_utf16(napi\_env env, napi\_value value, char16\_t\* buf, size\_t bufsize, size\_t\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript string. \* `[in] buf`: Buffer to write the UTF16-LE-encoded string into. If `NULL` is passed in, the length of the string in 2-byte code units and excluding the null terminator is returned. \* `[in] bufsize`: Size of the destination buffer. When this value is insufficient, the returned string is truncated and null-terminated. If this value is zero, then the string is not returned and no changes are done to the buffer. \* `[out] result`: Number of 2-byte code units copied into the buffer, excluding the null terminator. Returns `napi\_ok` if the API succeeded. If a non-`string` `napi\_value` is passed in it returns `napi\_string\_expected`. This API returns the UTF16-encoded string corresponding the value passed in. #### `napi\_get\_value\_uint32` ```c napi\_status napi\_get\_value\_uint32(napi\_env env, napi\_value value, uint32\_t\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: `napi\_value` representing JavaScript `number`. \* `[out] result`: C primitive equivalent of the given `napi\_value` as a `uint32\_t`. Returns `napi\_ok` if the API succeeded. If a non-number `napi\_value` is passed in it returns `napi\_number\_expected`. This API returns the C primitive equivalent of the given `napi\_value` as a `uint32\_t`. ### Functions to get global instances #### `napi\_get\_boolean` ```c napi\_status napi\_get\_boolean(napi\_env env, bool value, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The value of the boolean to retrieve. \* `[out] result`: `napi\_value` representing JavaScript `Boolean` singleton to retrieve. Returns `napi\_ok` if the API succeeded. This API is used to return the JavaScript singleton object that is used to represent the given boolean value. #### `napi\_get\_global` ```c napi\_status napi\_get\_global(napi\_env env, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: `napi\_value` representing JavaScript `global` object. Returns `napi\_ok` if the API succeeded. This API returns the `global` object. #### `napi\_get\_null` ```c napi\_status napi\_get\_null(napi\_env env, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: `napi\_value` representing JavaScript `null` object. Returns `napi\_ok` if the API succeeded. This API returns the `null` object. #### `napi\_get\_undefined` ```c napi\_status napi\_get\_undefined(napi\_env env, | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.03195776417851448,
0.07667919993400574,
-0.07655485719442368,
-0.023887701332569122,
-0.09267959743738174,
-0.06288541108369827,
0.05785517767071724,
0.048161737620830536,
-0.01778385601937771,
-0.07623365521430969,
-0.020390259101986885,
-0.09417581558227539,
0.02032851055264473,
-0.002... | 0.177236 |
returns the `global` object. #### `napi\_get\_null` ```c napi\_status napi\_get\_null(napi\_env env, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: `napi\_value` representing JavaScript `null` object. Returns `napi\_ok` if the API succeeded. This API returns the `null` object. #### `napi\_get\_undefined` ```c napi\_status napi\_get\_undefined(napi\_env env, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: `napi\_value` representing JavaScript Undefined value. Returns `napi\_ok` if the API succeeded. This API returns the Undefined object. ## Working with JavaScript values and abstract operations Node-API exposes a set of APIs to perform some abstract operations on JavaScript values. These APIs support doing one of the following: 1. Coerce JavaScript values to specific JavaScript types (such as `number` or `string`). 2. Check the type of a JavaScript value. 3. Check for equality between two JavaScript values. ### `napi\_coerce\_to\_bool` ```c napi\_status napi\_coerce\_to\_bool(napi\_env env, napi\_value value, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to coerce. \* `[out] result`: `napi\_value` representing the coerced JavaScript `Boolean`. Returns `napi\_ok` if the API succeeded. This API implements the abstract operation `ToBoolean()` as defined in [Section ToBoolean][] of the ECMAScript Language Specification. ### `napi\_coerce\_to\_number` ```c napi\_status napi\_coerce\_to\_number(napi\_env env, napi\_value value, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to coerce. \* `[out] result`: `napi\_value` representing the coerced JavaScript `number`. Returns `napi\_ok` if the API succeeded. This API implements the abstract operation `ToNumber()` as defined in [Section ToNumber][] of the ECMAScript Language Specification. This function potentially runs JS code if the passed-in value is an object. ### `napi\_coerce\_to\_object` ```c napi\_status napi\_coerce\_to\_object(napi\_env env, napi\_value value, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to coerce. \* `[out] result`: `napi\_value` representing the coerced JavaScript `Object`. Returns `napi\_ok` if the API succeeded. This API implements the abstract operation `ToObject()` as defined in [Section ToObject][] of the ECMAScript Language Specification. ### `napi\_coerce\_to\_string` ```c napi\_status napi\_coerce\_to\_string(napi\_env env, napi\_value value, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to coerce. \* `[out] result`: `napi\_value` representing the coerced JavaScript `string`. Returns `napi\_ok` if the API succeeded. This API implements the abstract operation `ToString()` as defined in [Section ToString][] of the ECMAScript Language Specification. This function potentially runs JS code if the passed-in value is an object. ### `napi\_typeof` ```c napi\_status napi\_typeof(napi\_env env, napi\_value value, napi\_valuetype\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value whose type to query. \* `[out] result`: The type of the JavaScript value. Returns `napi\_ok` if the API succeeded. \* `napi\_invalid\_arg` if the type of `value` is not a known ECMAScript type and `value` is not an External value. This API represents behavior similar to invoking the `typeof` Operator on the object as defined in [Section typeof operator][] of the ECMAScript Language Specification. However, there are some differences: 1. It has support for detecting an External value. 2. It detects `null` as a separate type, while ECMAScript `typeof` would detect `object`. If `value` has a type that is invalid, an error is returned. ### `napi\_instanceof` ```c napi\_status napi\_instanceof(napi\_env env, napi\_value object, napi\_value constructor, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] object`: The JavaScript value to check. \* `[in] constructor`: The JavaScript function object of the constructor function to check against. \* `[out] result`: Boolean that is | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.05674240365624428,
0.1062656044960022,
-0.019169382750988007,
0.013402458280324936,
-0.016211897134780884,
-0.07057294249534607,
-0.015880219638347626,
-0.0008803945383988321,
0.01840195618569851,
-0.09299879521131516,
0.0023712997790426016,
-0.07286619395017624,
-0.029528265818953514,
... | 0.165877 |
```c napi\_status napi\_instanceof(napi\_env env, napi\_value object, napi\_value constructor, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] object`: The JavaScript value to check. \* `[in] constructor`: The JavaScript function object of the constructor function to check against. \* `[out] result`: Boolean that is set to true if `object instanceof constructor` is true. Returns `napi\_ok` if the API succeeded. This API represents invoking the `instanceof` Operator on the object as defined in [Section instanceof operator][] of the ECMAScript Language Specification. ### `napi\_is\_array` ```c napi\_status napi\_is\_array(napi\_env env, napi\_value value, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to check. \* `[out] result`: Whether the given object is an array. Returns `napi\_ok` if the API succeeded. This API represents invoking the `IsArray` operation on the object as defined in [Section IsArray][] of the ECMAScript Language Specification. ### `napi\_is\_arraybuffer` ```c napi\_status napi\_is\_arraybuffer(napi\_env env, napi\_value value, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to check. \* `[out] result`: Whether the given object is an `ArrayBuffer`. Returns `napi\_ok` if the API succeeded. This API checks if the `Object` passed in is an array buffer. ### `napi\_is\_buffer` ```c napi\_status napi\_is\_buffer(napi\_env env, napi\_value value, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to check. \* `[out] result`: Whether the given `napi\_value` represents a `node::Buffer` or `Uint8Array` object. Returns `napi\_ok` if the API succeeded. This API checks if the `Object` passed in is a buffer or Uint8Array. [`napi\_is\_typedarray`][] should be preferred if the caller needs to check if the value is a Uint8Array. ### `napi\_is\_date` ```c napi\_status napi\_is\_date(napi\_env env, napi\_value value, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to check. \* `[out] result`: Whether the given `napi\_value` represents a JavaScript `Date` object. Returns `napi\_ok` if the API succeeded. This API checks if the `Object` passed in is a date. ### `napi\_is\_error` ```c napi\_status napi\_is\_error(napi\_env env, napi\_value value, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to check. \* `[out] result`: Whether the given `napi\_value` represents an `Error` object. Returns `napi\_ok` if the API succeeded. This API checks if the `Object` passed in is an `Error`. ### `napi\_is\_typedarray` ```c napi\_status napi\_is\_typedarray(napi\_env env, napi\_value value, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to check. \* `[out] result`: Whether the given `napi\_value` represents a `TypedArray`. Returns `napi\_ok` if the API succeeded. This API checks if the `Object` passed in is a typed array. ### `napi\_is\_dataview` ```c napi\_status napi\_is\_dataview(napi\_env env, napi\_value value, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to check. \* `[out] result`: Whether the given `napi\_value` represents a `DataView`. Returns `napi\_ok` if the API succeeded. This API checks if the `Object` passed in is a `DataView`. ### `napi\_strict\_equals` ```c napi\_status napi\_strict\_equals(napi\_env env, napi\_value lhs, napi\_value rhs, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] lhs`: The JavaScript value to check. \* `[in] rhs`: The JavaScript value to check against. \* `[out] result`: Whether the two `napi\_value` objects are equal. Returns `napi\_ok` if the API succeeded. This API represents the invocation of the Strict Equality algorithm as defined in [Section IsStrctEqual][] of the ECMAScript Language Specification. ### `napi\_detach\_arraybuffer` ```c | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.0044042798690497875,
0.10878553241491318,
-0.0009672304149717093,
-0.0008300825138576329,
-0.02517952024936676,
-0.07104532420635223,
0.06349718570709229,
-0.032837577164173126,
-0.023680029436945915,
-0.06526470184326172,
-0.06215362995862961,
-0.06815507262945175,
-0.02299186773598194,
... | 0.2042 |
to check. \* `[in] rhs`: The JavaScript value to check against. \* `[out] result`: Whether the two `napi\_value` objects are equal. Returns `napi\_ok` if the API succeeded. This API represents the invocation of the Strict Equality algorithm as defined in [Section IsStrctEqual][] of the ECMAScript Language Specification. ### `napi\_detach\_arraybuffer` ```c napi\_status napi\_detach\_arraybuffer(napi\_env env, napi\_value arraybuffer) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] arraybuffer`: The JavaScript `ArrayBuffer` to be detached. Returns `napi\_ok` if the API succeeded. If a non-detachable `ArrayBuffer` is passed in it returns `napi\_detachable\_arraybuffer\_expected`. Generally, an `ArrayBuffer` is non-detachable if it has been detached before. The engine may impose additional conditions on whether an `ArrayBuffer` is detachable. For example, V8 requires that the `ArrayBuffer` be external, that is, created with [`napi\_create\_external\_arraybuffer`][]. This API represents the invocation of the `ArrayBuffer` detach operation as defined in [Section detachArrayBuffer][] of the ECMAScript Language Specification. ### `napi\_is\_detached\_arraybuffer` ```c napi\_status napi\_is\_detached\_arraybuffer(napi\_env env, napi\_value arraybuffer, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] arraybuffer`: The JavaScript `ArrayBuffer` to be checked. \* `[out] result`: Whether the `arraybuffer` is detached. Returns `napi\_ok` if the API succeeded. The `ArrayBuffer` is considered detached if its internal data is `null`. This API represents the invocation of the `ArrayBuffer` `IsDetachedBuffer` operation as defined in [Section isDetachedBuffer][] of the ECMAScript Language Specification. ### `node\_api\_is\_sharedarraybuffer` > Stability: 1 - Experimental ```c napi\_status node\_api\_is\_sharedarraybuffer(napi\_env env, napi\_value value, bool\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The JavaScript value to check. \* `[out] result`: Whether the given `napi\_value` represents a `SharedArrayBuffer`. Returns `napi\_ok` if the API succeeded. This API checks if the Object passed in is a `SharedArrayBuffer`. ### `node\_api\_create\_sharedarraybuffer` > Stability: 1 - Experimental ```c napi\_status node\_api\_create\_sharedarraybuffer(napi\_env env, size\_t byte\_length, void\*\* data, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] byte\_length`: The length in bytes of the shared array buffer to create. \* `[out] data`: Pointer to the underlying byte buffer of the `SharedArrayBuffer`. `data` can optionally be ignored by passing `NULL`. \* `[out] result`: A `napi\_value` representing a JavaScript `SharedArrayBuffer`. Returns `napi\_ok` if the API succeeded. This API returns a Node-API value corresponding to a JavaScript `SharedArrayBuffer`. `SharedArrayBuffer`s are used to represent fixed-length binary data buffers that can be shared across multiple workers. The `SharedArrayBuffer` allocated will have an underlying byte buffer whose size is determined by the `byte\_length` parameter that's passed in. The underlying buffer is optionally returned back to the caller in case the caller wants to directly manipulate the buffer. This buffer can only be written to directly from native code. To write to this buffer from JavaScript, a typed array or `DataView` object would need to be created. JavaScript `SharedArrayBuffer` objects are described in [Section SharedArrayBuffer objects][] of the ECMAScript Language Specification. ## Working with JavaScript properties Node-API exposes a set of APIs to get and set properties on JavaScript objects. Properties in JavaScript are represented as a tuple of a key and a value. Fundamentally, all property keys in Node-API can be represented in one of the following forms: \* Named: a simple UTF8-encoded string \* Integer-Indexed: an index value represented by `uint32\_t` \* JavaScript value: these are represented in Node-API by `napi\_value`. This can be a `napi\_value` representing a `string`, `number`, or `symbol`. Node-API values are represented by the type `napi\_value`. Any Node-API call that requires a JavaScript value takes in a `napi\_value`. However, it's the caller's responsibility to make sure that the `napi\_value` in question is of the JavaScript type expected by the API. | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.01404173206537962,
0.059832122176885605,
-0.02751888893544674,
-0.011436370201408863,
-0.0014614745741710067,
-0.08755538612604141,
0.04993981122970581,
-0.06098609045147896,
-0.024794239550828934,
-0.09413640201091766,
-0.036400146782398224,
-0.02507513202726841,
0.011968868784606457,
... | 0.189094 |
a `napi\_value` representing a `string`, `number`, or `symbol`. Node-API values are represented by the type `napi\_value`. Any Node-API call that requires a JavaScript value takes in a `napi\_value`. However, it's the caller's responsibility to make sure that the `napi\_value` in question is of the JavaScript type expected by the API. The APIs documented in this section provide a simple interface to get and set properties on arbitrary JavaScript objects represented by `napi\_value`. For instance, consider the following JavaScript code snippet: ```js const obj = {}; obj.myProp = 123; ``` The equivalent can be done using Node-API values with the following snippet: ```c napi\_status status = napi\_generic\_failure; // const obj = {} napi\_value obj, value; status = napi\_create\_object(env, &obj); if (status != napi\_ok) return status; // Create a napi\_value for 123 status = napi\_create\_int32(env, 123, &value); if (status != napi\_ok) return status; // obj.myProp = 123 status = napi\_set\_named\_property(env, obj, "myProp", value); if (status != napi\_ok) return status; ``` Indexed properties can be set in a similar manner. Consider the following JavaScript snippet: ```js const arr = []; arr[123] = 'hello'; ``` The equivalent can be done using Node-API values with the following snippet: ```c napi\_status status = napi\_generic\_failure; // const arr = []; napi\_value arr, value; status = napi\_create\_array(env, &arr); if (status != napi\_ok) return status; // Create a napi\_value for 'hello' status = napi\_create\_string\_utf8(env, "hello", NAPI\_AUTO\_LENGTH, &value); if (status != napi\_ok) return status; // arr[123] = 'hello'; status = napi\_set\_element(env, arr, 123, value); if (status != napi\_ok) return status; ``` Properties can be retrieved using the APIs described in this section. Consider the following JavaScript snippet: ```js const arr = []; const value = arr[123]; ``` The following is the approximate equivalent of the Node-API counterpart: ```c napi\_status status = napi\_generic\_failure; // const arr = [] napi\_value arr, value; status = napi\_create\_array(env, &arr); if (status != napi\_ok) return status; // const value = arr[123] status = napi\_get\_element(env, arr, 123, &value); if (status != napi\_ok) return status; ``` Finally, multiple properties can also be defined on an object for performance reasons. Consider the following JavaScript: ```js const obj = {}; Object.defineProperties(obj, { 'foo': { value: 123, writable: true, configurable: true, enumerable: true }, 'bar': { value: 456, writable: true, configurable: true, enumerable: true }, }); ``` The following is the approximate equivalent of the Node-API counterpart: ```c napi\_status status = napi\_status\_generic\_failure; // const obj = {}; napi\_value obj; status = napi\_create\_object(env, &obj); if (status != napi\_ok) return status; // Create napi\_values for 123 and 456 napi\_value fooValue, barValue; status = napi\_create\_int32(env, 123, &fooValue); if (status != napi\_ok) return status; status = napi\_create\_int32(env, 456, &barValue); if (status != napi\_ok) return status; // Set the properties napi\_property\_descriptor descriptors[] = { { "foo", NULL, NULL, NULL, NULL, fooValue, napi\_writable | napi\_configurable, NULL }, { "bar", NULL, NULL, NULL, NULL, barValue, napi\_writable | napi\_configurable, NULL } } status = napi\_define\_properties(env, obj, sizeof(descriptors) / sizeof(descriptors[0]), descriptors); if (status != napi\_ok) return status; ``` ### Structures #### `napi\_property\_attributes` ```c typedef enum { napi\_default = 0, napi\_writable = 1 << 0, napi\_enumerable = 1 << 1, napi\_configurable = 1 << 2, // Used with napi\_define\_class to distinguish static properties // from instance properties. Ignored by napi\_define\_properties. napi\_static = 1 << 10, // Default for class methods. napi\_default\_method = napi\_writable | napi\_configurable, // Default for object properties, like in JS obj[prop]. napi\_default\_jsproperty = napi\_writable | napi\_enumerable | napi\_configurable, } napi\_property\_attributes; ``` `napi\_property\_attributes` are bit flags used to control the behavior of properties set on a JavaScript object. Other than `napi\_static` they correspond to the attributes listed in [Section property attributes][] of the [ECMAScript Language Specification][]. They can be | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.0640469342470169,
0.12102567404508591,
0.020117467269301414,
0.05235275253653526,
-0.060448773205280304,
-0.007620209828019142,
0.03593209758400917,
0.002723621902987361,
0.051260631531476974,
-0.08766499161720276,
-0.08479344844818115,
-0.029016466811299324,
-0.02357216365635395,
-0.00... | 0.167142 |
in JS obj[prop]. napi\_default\_jsproperty = napi\_writable | napi\_enumerable | napi\_configurable, } napi\_property\_attributes; ``` `napi\_property\_attributes` are bit flags used to control the behavior of properties set on a JavaScript object. Other than `napi\_static` they correspond to the attributes listed in [Section property attributes][] of the [ECMAScript Language Specification][]. They can be one or more of the following bit flags: \* `napi\_default`: No explicit attributes are set on the property. By default, a property is read only, not enumerable and not configurable. \* `napi\_writable`: The property is writable. \* `napi\_enumerable`: The property is enumerable. \* `napi\_configurable`: The property is configurable as defined in [Section property attributes][] of the [ECMAScript Language Specification][]. \* `napi\_static`: The property will be defined as a static property on a class as opposed to an instance property, which is the default. This is used only by [`napi\_define\_class`][]. It is ignored by `napi\_define\_properties`. \* `napi\_default\_method`: Like a method in a JS class, the property is configurable and writeable, but not enumerable. \* `napi\_default\_jsproperty`: Like a property set via assignment in JavaScript, the property is writable, enumerable, and configurable. #### `napi\_property\_descriptor` ```c typedef struct { // One of utf8name or name should be NULL. const char\* utf8name; napi\_value name; napi\_callback method; napi\_callback getter; napi\_callback setter; napi\_value value; napi\_property\_attributes attributes; void\* data; } napi\_property\_descriptor; ``` \* `utf8name`: Optional string describing the key for the property, encoded as UTF8. One of `utf8name` or `name` must be provided for the property. \* `name`: Optional `napi\_value` that points to a JavaScript string or symbol to be used as the key for the property. One of `utf8name` or `name` must be provided for the property. \* `value`: The value that's retrieved by a get access of the property if the property is a data property. If this is passed in, set `getter`, `setter`, `method` and `data` to `NULL` (since these members won't be used). \* `getter`: A function to call when a get access of the property is performed. If this is passed in, set `value` and `method` to `NULL` (since these members won't be used). The given function is called implicitly by the runtime when the property is accessed from JavaScript code (or if a get on the property is performed using a Node-API call). [`napi\_callback`][] provides more details. \* `setter`: A function to call when a set access of the property is performed. If this is passed in, set `value` and `method` to `NULL` (since these members won't be used). The given function is called implicitly by the runtime when the property is set from JavaScript code (or if a set on the property is performed using a Node-API call). [`napi\_callback`][] provides more details. \* `method`: Set this to make the property descriptor object's `value` property to be a JavaScript function represented by `method`. If this is passed in, set `value`, `getter` and `setter` to `NULL` (since these members won't be used). [`napi\_callback`][] provides more details. \* `attributes`: The attributes associated with the particular property. See [`napi\_property\_attributes`][]. \* `data`: The callback data passed into `method`, `getter` and `setter` if this function is invoked. ### Functions #### `napi\_get\_property\_names` ```c napi\_status napi\_get\_property\_names(napi\_env env, napi\_value object, napi\_value\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object from which to retrieve the properties. \* `[out] result`: A `napi\_value` representing an array of JavaScript values that represent the property names of the object. The API can be used to iterate over `result` using [`napi\_get\_array\_length`][] and [`napi\_get\_element`][]. Returns `napi\_ok` if the API succeeded. This API returns the names of the enumerable properties of `object` as an array of strings. | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.01716817170381546,
0.09575891494750977,
-0.03643302991986275,
0.058590278029441833,
-0.0006376352393999696,
0.003306227270513773,
0.07432974874973297,
-0.021697191521525383,
-0.03561224043369293,
-0.08725619316101074,
0.00041545138810761273,
-0.012129038572311401,
-0.037601251155138016,
... | 0.207089 |
`napi\_value` representing an array of JavaScript values that represent the property names of the object. The API can be used to iterate over `result` using [`napi\_get\_array\_length`][] and [`napi\_get\_element`][]. Returns `napi\_ok` if the API succeeded. This API returns the names of the enumerable properties of `object` as an array of strings. The properties of `object` whose key is a symbol will not be included. #### `napi\_get\_all\_property\_names` ```c napi\_get\_all\_property\_names(napi\_env env, napi\_value object, napi\_key\_collection\_mode key\_mode, napi\_key\_filter key\_filter, napi\_key\_conversion key\_conversion, napi\_value\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object from which to retrieve the properties. \* `[in] key\_mode`: Whether to retrieve prototype properties as well. \* `[in] key\_filter`: Which properties to retrieve (enumerable/readable/writable). \* `[in] key\_conversion`: Whether to convert numbered property keys to strings. \* `[out] result`: A `napi\_value` representing an array of JavaScript values that represent the property names of the object. [`napi\_get\_array\_length`][] and [`napi\_get\_element`][] can be used to iterate over `result`. Returns `napi\_ok` if the API succeeded. This API returns an array containing the names of the available properties of this object. #### `napi\_set\_property` ```c napi\_status napi\_set\_property(napi\_env env, napi\_value object, napi\_value key, napi\_value value); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object on which to set the property. \* `[in] key`: The name of the property to set. \* `[in] value`: The property value. Returns `napi\_ok` if the API succeeded. This API set a property on the `Object` passed in. #### `napi\_get\_property` ```c napi\_status napi\_get\_property(napi\_env env, napi\_value object, napi\_value key, napi\_value\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object from which to retrieve the property. \* `[in] key`: The name of the property to retrieve. \* `[out] result`: The value of the property. Returns `napi\_ok` if the API succeeded. This API gets the requested property from the `Object` passed in. #### `napi\_has\_property` ```c napi\_status napi\_has\_property(napi\_env env, napi\_value object, napi\_value key, bool\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object to query. \* `[in] key`: The name of the property whose existence to check. \* `[out] result`: Whether the property exists on the object or not. Returns `napi\_ok` if the API succeeded. This API checks if the `Object` passed in has the named property. #### `napi\_delete\_property` ```c napi\_status napi\_delete\_property(napi\_env env, napi\_value object, napi\_value key, bool\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object to query. \* `[in] key`: The name of the property to delete. \* `[out] result`: Whether the property deletion succeeded or not. `result` can optionally be ignored by passing `NULL`. Returns `napi\_ok` if the API succeeded. This API attempts to delete the `key` own property from `object`. #### `napi\_has\_own\_property` ```c napi\_status napi\_has\_own\_property(napi\_env env, napi\_value object, napi\_value key, bool\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object to query. \* `[in] key`: The name of the own property whose existence to check. \* `[out] result`: Whether the own property exists on the object or not. Returns `napi\_ok` if the API succeeded. This API checks if the `Object` passed in has the named own property. `key` must be a `string` or a `symbol`, or an error will be thrown. Node-API will not perform any conversion between data types. #### `napi\_set\_named\_property` ```c napi\_status napi\_set\_named\_property(napi\_env env, napi\_value object, const char\* utf8Name, napi\_value value); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.02134229801595211,
0.14667320251464844,
-0.015786049887537956,
0.06732936203479767,
-0.05405557528138161,
-0.026489919051527977,
0.035087935626506805,
-0.010922564193606377,
0.019190208986401558,
-0.09352090954780579,
-0.04366337135434151,
-0.07856860756874084,
0.011922075413167477,
-0.0... | 0.143195 |
be a `string` or a `symbol`, or an error will be thrown. Node-API will not perform any conversion between data types. #### `napi\_set\_named\_property` ```c napi\_status napi\_set\_named\_property(napi\_env env, napi\_value object, const char\* utf8Name, napi\_value value); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object on which to set the property. \* `[in] utf8Name`: The name of the property to set. \* `[in] value`: The property value. Returns `napi\_ok` if the API succeeded. This method is equivalent to calling [`napi\_set\_property`][] with a `napi\_value` created from the string passed in as `utf8Name`. #### `napi\_get\_named\_property` ```c napi\_status napi\_get\_named\_property(napi\_env env, napi\_value object, const char\* utf8Name, napi\_value\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object from which to retrieve the property. \* `[in] utf8Name`: The name of the property to get. \* `[out] result`: The value of the property. Returns `napi\_ok` if the API succeeded. This method is equivalent to calling [`napi\_get\_property`][] with a `napi\_value` created from the string passed in as `utf8Name`. #### `napi\_has\_named\_property` ```c napi\_status napi\_has\_named\_property(napi\_env env, napi\_value object, const char\* utf8Name, bool\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object to query. \* `[in] utf8Name`: The name of the property whose existence to check. \* `[out] result`: Whether the property exists on the object or not. Returns `napi\_ok` if the API succeeded. This method is equivalent to calling [`napi\_has\_property`][] with a `napi\_value` created from the string passed in as `utf8Name`. #### `napi\_set\_element` ```c napi\_status napi\_set\_element(napi\_env env, napi\_value object, uint32\_t index, napi\_value value); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object from which to set the properties. \* `[in] index`: The index of the property to set. \* `[in] value`: The property value. Returns `napi\_ok` if the API succeeded. This API sets an element on the `Object` passed in. #### `napi\_get\_element` ```c napi\_status napi\_get\_element(napi\_env env, napi\_value object, uint32\_t index, napi\_value\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object from which to retrieve the property. \* `[in] index`: The index of the property to get. \* `[out] result`: The value of the property. Returns `napi\_ok` if the API succeeded. This API gets the element at the requested index. #### `napi\_has\_element` ```c napi\_status napi\_has\_element(napi\_env env, napi\_value object, uint32\_t index, bool\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object to query. \* `[in] index`: The index of the property whose existence to check. \* `[out] result`: Whether the property exists on the object or not. Returns `napi\_ok` if the API succeeded. This API returns if the `Object` passed in has an element at the requested index. #### `napi\_delete\_element` ```c napi\_status napi\_delete\_element(napi\_env env, napi\_value object, uint32\_t index, bool\* result); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object to query. \* `[in] index`: The index of the property to delete. \* `[out] result`: Whether the element deletion succeeded or not. `result` can optionally be ignored by passing `NULL`. Returns `napi\_ok` if the API succeeded. This API attempts to delete the specified `index` from `object`. #### `napi\_define\_properties` ```c napi\_status napi\_define\_properties(napi\_env env, napi\_value object, size\_t property\_count, const napi\_property\_descriptor\* properties); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object from which to retrieve the properties. \* `[in] property\_count`: The number of elements in the `properties` array. \* `[in] properties`: The | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
0.008110316470265388,
0.1183064803481102,
-0.01900859735906124,
0.07437733560800552,
-0.11778369545936584,
-0.03073623590171337,
0.017380695790052414,
0.01819191873073578,
-0.03381805121898651,
-0.039657726883888245,
-0.06579608470201492,
-0.09839324653148651,
0.027787357568740845,
-0.0325... | 0.134031 |
```c napi\_status napi\_define\_properties(napi\_env env, napi\_value object, size\_t property\_count, const napi\_property\_descriptor\* properties); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object from which to retrieve the properties. \* `[in] property\_count`: The number of elements in the `properties` array. \* `[in] properties`: The array of property descriptors. Returns `napi\_ok` if the API succeeded. This method allows the efficient definition of multiple properties on a given object. The properties are defined using property descriptors (see [`napi\_property\_descriptor`][]). Given an array of such property descriptors, this API will set the properties on the object one at a time, as defined by `DefineOwnProperty()` (described in [Section DefineOwnProperty][] of the ECMA-262 specification). #### `napi\_object\_freeze` ```c napi\_status napi\_object\_freeze(napi\_env env, napi\_value object); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object to freeze. Returns `napi\_ok` if the API succeeded. This method freezes a given object. This prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. It also prevents the object's prototype from being changed. This is described in [Section 19.1.2.6](https://tc39.es/ecma262/#sec-object.freeze) of the ECMA-262 specification. #### `napi\_object\_seal` ```c napi\_status napi\_object\_seal(napi\_env env, napi\_value object); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object to seal. Returns `napi\_ok` if the API succeeded. This method seals a given object. This prevents new properties from being added to it, as well as marking all existing properties as non-configurable. This is described in [Section 19.1.2.20](https://tc39.es/ecma262/#sec-object.seal) of the ECMA-262 specification. #### `node\_api\_set\_prototype` > Stability: 1 - Experimental ```c napi\_status node\_api\_set\_prototype(napi\_env env, napi\_value object, napi\_value value); ``` \* `[in] env`: The environment that the Node-API call is invoked under. \* `[in] object`: The object on which to set the prototype. \* `[in] value`: The prototype value. Returns `napi\_ok` if the API succeeded. This API sets the prototype of the `Object` passed in. ## Working with JavaScript functions Node-API provides a set of APIs that allow JavaScript code to call back into native code. Node-APIs that support calling back into native code take in a callback functions represented by the `napi\_callback` type. When the JavaScript VM calls back to native code, the `napi\_callback` function provided is invoked. The APIs documented in this section allow the callback function to do the following: \* Get information about the context in which the callback was invoked. \* Get the arguments passed into the callback. \* Return a `napi\_value` back from the callback. Additionally, Node-API provides a set of functions which allow calling JavaScript functions from native code. One can either call a function like a regular JavaScript function call, or as a constructor function. Any non-`NULL` data which is passed to this API via the `data` field of the `napi\_property\_descriptor` items can be associated with `object` and freed whenever `object` is garbage-collected by passing both `object` and the data to [`napi\_add\_finalizer`][]. ### `napi\_call\_function` ```c NAPI\_EXTERN napi\_status napi\_call\_function(napi\_env env, napi\_value recv, napi\_value func, size\_t argc, const napi\_value\* argv, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] recv`: The `this` value passed to the called function. \* `[in] func`: `napi\_value` representing the JavaScript function to be invoked. \* `[in] argc`: The count of elements in the `argv` array. \* `[in] argv`: Array of `napi\_values` representing JavaScript values passed in as arguments to the function. \* `[out] result`: `napi\_value` representing the JavaScript object returned. Returns `napi\_ok` if the API succeeded. This method allows a JavaScript | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.00787839200347662,
0.12590207159519196,
-0.03071495331823826,
0.08790425211191177,
-0.051006291061639786,
-0.03146262839436531,
0.028949102386832237,
-0.03728337213397026,
0.014095845632255077,
-0.04246632754802704,
-0.045745428651571274,
-0.10618377476930618,
0.030584534630179405,
-0.0... | 0.159661 |
to be invoked. \* `[in] argc`: The count of elements in the `argv` array. \* `[in] argv`: Array of `napi\_values` representing JavaScript values passed in as arguments to the function. \* `[out] result`: `napi\_value` representing the JavaScript object returned. Returns `napi\_ok` if the API succeeded. This method allows a JavaScript function object to be called from a native add-on. This is the primary mechanism of calling back \_from\_ the add-on's native code \_into\_ JavaScript. For the special case of calling into JavaScript after an async operation, see [`napi\_make\_callback`][]. A sample use case might look as follows. Consider the following JavaScript snippet: ```js function AddTwo(num) { return num + 2; } global.AddTwo = AddTwo; ``` Then, the above function can be invoked from a native add-on using the following code: ```c // Get the function named "AddTwo" on the global object napi\_value global, add\_two, arg; napi\_status status = napi\_get\_global(env, &global); if (status != napi\_ok) return; status = napi\_get\_named\_property(env, global, "AddTwo", &add\_two); if (status != napi\_ok) return; // const arg = 1337 status = napi\_create\_int32(env, 1337, &arg); if (status != napi\_ok) return; napi\_value\* argv = &arg size\_t argc = 1; // AddTwo(arg); napi\_value return\_val; status = napi\_call\_function(env, global, add\_two, argc, argv, &return\_val); if (status != napi\_ok) return; // Convert the result back to a native type int32\_t result; status = napi\_get\_value\_int32(env, return\_val, &result); if (status != napi\_ok) return; ``` ### `napi\_create\_function` ```c napi\_status napi\_create\_function(napi\_env env, const char\* utf8name, size\_t length, napi\_callback cb, void\* data, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] utf8Name`: Optional name of the function encoded as UTF8. This is visible within JavaScript as the new function object's `name` property. \* `[in] length`: The length of the `utf8name` in bytes, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[in] cb`: The native function which should be called when this function object is invoked. [`napi\_callback`][] provides more details. \* `[in] data`: User-provided data context. This will be passed back into the function when invoked later. \* `[out] result`: `napi\_value` representing the JavaScript function object for the newly created function. Returns `napi\_ok` if the API succeeded. 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. In order to expose a function as part of the add-on's module exports, set the newly created function on the exports object. A sample module might look as follows: ```c napi\_value SayHello(napi\_env env, napi\_callback\_info info) { printf("Hello\n"); return NULL; } napi\_value Init(napi\_env env, napi\_value exports) { napi\_status status; napi\_value fn; status = napi\_create\_function(env, NULL, 0, SayHello, NULL, &fn); if (status != napi\_ok) return NULL; status = napi\_set\_named\_property(env, exports, "sayHello", fn); if (status != napi\_ok) return NULL; return exports; } NAPI\_MODULE(NODE\_GYP\_MODULE\_NAME, Init) ``` Given the above code, the add-on can be used from JavaScript as follows: ```js const myaddon = require('./addon'); myaddon.sayHello(); ``` The string passed to `require()` is the name of the target in `binding.gyp` responsible for creating the `.node` file. Any non-`NULL` data which is passed to this API via the `data` parameter can be associated with the resulting JavaScript function (which is returned in the `result` parameter) and freed whenever the function is garbage-collected by passing both the JavaScript function and the data to [`napi\_add\_finalizer`][]. JavaScript `Function`s are described in [Section Function objects][] of the ECMAScript Language Specification. ### | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.12042956799268723,
0.031827669590711594,
-0.05883850157260895,
0.09670863300561905,
-0.0739329382777214,
-0.034097474068403244,
0.07805748283863068,
-0.002539976267144084,
0.05551091954112053,
-0.10694827884435654,
-0.03395787626504898,
0.030613373965024948,
-0.05255092680454254,
-0.039... | 0.188897 |
the `data` parameter can be associated with the resulting JavaScript function (which is returned in the `result` parameter) and freed whenever the function is garbage-collected by passing both the JavaScript function and the data to [`napi\_add\_finalizer`][]. JavaScript `Function`s are described in [Section Function objects][] of the ECMAScript Language Specification. ### `napi\_get\_cb\_info` ```c napi\_status napi\_get\_cb\_info(napi\_env env, napi\_callback\_info cbinfo, size\_t\* argc, napi\_value\* argv, napi\_value\* thisArg, void\*\* data) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] cbinfo`: The callback info passed into the callback function. \* `[in-out] argc`: Specifies the length of the provided `argv` array and receives the actual count of arguments. `argc` can optionally be ignored by passing `NULL`. \* `[out] argv`: C array of `napi\_value`s to which the arguments will be copied. If there are more arguments than the provided count, only the requested number of arguments are copied. If there are fewer arguments provided than claimed, the rest of `argv` is filled with `napi\_value` values that represent `undefined`. `argv` can optionally be ignored by passing `NULL`. \* `[out] thisArg`: Receives the JavaScript `this` argument for the call. `thisArg` can optionally be ignored by passing `NULL`. \* `[out] data`: Receives the data pointer for the callback. `data` can optionally be ignored by passing `NULL`. Returns `napi\_ok` if the API succeeded. This method is used within a callback function to retrieve details about the call like the arguments and the `this` pointer from a given callback info. ### `napi\_get\_new\_target` ```c napi\_status napi\_get\_new\_target(napi\_env env, napi\_callback\_info cbinfo, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] cbinfo`: The callback info passed into the callback function. \* `[out] result`: The `new.target` of the constructor call. Returns `napi\_ok` if the API succeeded. This API returns the `new.target` of the constructor call. If the current callback is not a constructor call, the result is `NULL`. ### `napi\_new\_instance` ```c napi\_status napi\_new\_instance(napi\_env env, napi\_value cons, size\_t argc, napi\_value\* argv, napi\_value\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] cons`: `napi\_value` representing the JavaScript function to be invoked as a constructor. \* `[in] argc`: The count of elements in the `argv` array. \* `[in] argv`: Array of JavaScript values as `napi\_value` representing the arguments to the constructor. If `argc` is zero this parameter may be omitted by passing in `NULL`. \* `[out] result`: `napi\_value` representing the JavaScript object returned, which in this case is the constructed object. This method is used to instantiate a new JavaScript value using a given `napi\_value` that represents the constructor for the object. For example, consider the following snippet: ```js function MyObject(param) { this.param = param; } const arg = 'hello'; const value = new MyObject(arg); ``` The following can be approximated in Node-API using the following snippet: ```c // Get the constructor function MyObject napi\_value global, constructor, arg, value; napi\_status status = napi\_get\_global(env, &global); if (status != napi\_ok) return; status = napi\_get\_named\_property(env, global, "MyObject", &constructor); if (status != napi\_ok) return; // const arg = "hello" status = napi\_create\_string\_utf8(env, "hello", NAPI\_AUTO\_LENGTH, &arg); if (status != napi\_ok) return; napi\_value\* argv = &arg size\_t argc = 1; // const value = new MyObject(arg) status = napi\_new\_instance(env, constructor, argc, argv, &value); ``` Returns `napi\_ok` if the API succeeded. ## Object wrap Node-API offers a way to "wrap" C++ classes and instances so that the class constructor and methods can be called from JavaScript. 1. The [`napi\_define\_class`][] API defines a JavaScript class with constructor, static properties and methods, and instance properties and methods that correspond to the C++ class. 2. When JavaScript code invokes the constructor, the constructor | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.0068204146809875965,
0.14576222002506256,
-0.03131196275353432,
0.043036602437496185,
-0.032554544508457184,
-0.06910881400108337,
0.04546694830060005,
0.07488109916448593,
-0.016702700406312943,
-0.09232637286186218,
-0.0057043335400521755,
-0.04087817296385765,
-0.018456928431987762,
... | 0.234336 |
C++ classes and instances so that the class constructor and methods can be called from JavaScript. 1. The [`napi\_define\_class`][] API defines a JavaScript class with constructor, static properties and methods, and instance properties and methods that correspond to the C++ class. 2. When JavaScript code invokes the constructor, the constructor callback uses [`napi\_wrap`][] to wrap a new C++ instance in a JavaScript object, then returns the wrapper object. 3. When JavaScript code invokes a method or property accessor on the class, the corresponding `napi\_callback` C++ function is invoked. For an instance callback, [`napi\_unwrap`][] obtains the C++ instance that is the target of the call. For wrapped objects it may be difficult to distinguish between a function called on a class prototype and a function called on an instance of a class. A common pattern used to address this problem is to save a persistent reference to the class constructor for later `instanceof` checks. ```c napi\_value MyClass\_constructor = NULL; status = napi\_get\_reference\_value(env, MyClass::es\_constructor, &MyClass\_constructor); assert(napi\_ok == status); bool is\_instance = false; status = napi\_instanceof(env, es\_this, MyClass\_constructor, &is\_instance); assert(napi\_ok == status); if (is\_instance) { // napi\_unwrap() ... } else { // otherwise... } ``` The reference must be freed once it is no longer needed. There are occasions where `napi\_instanceof()` is insufficient for ensuring that a JavaScript object is a wrapper for a certain native type. This is the case especially when wrapped JavaScript objects are passed back into the addon via static methods rather than as the `this` value of prototype methods. In such cases there is a chance that they may be unwrapped incorrectly. ```js const myAddon = require('./build/Release/my\_addon.node'); // `openDatabase()` returns a JavaScript object that wraps a native database // handle. const dbHandle = myAddon.openDatabase(); // `query()` returns a JavaScript object that wraps a native query handle. const queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!'); // There is an accidental error in the line below. The first parameter to // `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not // the query handle (`query`), so the correct condition for the while-loop // should be // // myAddon.queryHasRecords(dbHandle, queryHandle) // while (myAddon.queryHasRecords(queryHandle, dbHandle)) { // retrieve records } ``` In the above example `myAddon.queryHasRecords()` is a method that accepts two arguments. The first is a database handle and the second is a query handle. Internally, it unwraps the first argument and casts the resulting pointer to a native database handle. It then unwraps the second argument and casts the resulting pointer to a query handle. If the arguments are passed in the wrong order, the casts will work, however, there is a good chance that the underlying database operation will fail, or will even cause an invalid memory access. To ensure that the pointer retrieved from the first argument is indeed a pointer to a database handle and, similarly, that the pointer retrieved from the second argument is indeed a pointer to a query handle, the implementation of `queryHasRecords()` has to perform a type validation. Retaining the JavaScript class constructor from which the database handle was instantiated and the constructor from which the query handle was instantiated in `napi\_ref`s can help, because `napi\_instanceof()` can then be used to ensure that the instances passed into `queryHashRecords()` are indeed of the correct type. Unfortunately, `napi\_instanceof()` does not protect against prototype manipulation. For example, the prototype of the database handle instance can be set to the prototype of the constructor for query handle instances. In this case, the database handle instance can appear as a query handle instance, and it will pass the `napi\_instanceof()` test for a query handle instance, while still containing a | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.15311883389949799,
0.0664457380771637,
-0.023155078291893005,
0.044130828231573105,
-0.012546476908028126,
-0.017061909660696983,
0.039947301149368286,
-0.03879626840353012,
0.03128692880272865,
-0.059249147772789,
-0.007875648327171803,
0.021755574271082878,
-0.06748581677675247,
-0.04... | 0.143408 |
the prototype of the database handle instance can be set to the prototype of the constructor for query handle instances. In this case, the database handle instance can appear as a query handle instance, and it will pass the `napi\_instanceof()` test for a query handle instance, while still containing a pointer to a database handle. To this end, Node-API provides type-tagging capabilities. A type tag is a 128-bit integer unique to the addon. Node-API provides the `napi\_type\_tag` structure for storing a type tag. When such a value is passed along with a JavaScript object or [external][] stored in a `napi\_value` to `napi\_type\_tag\_object()`, the JavaScript object will be "marked" with the type tag. The "mark" is invisible on the JavaScript side. When a JavaScript object arrives into a native binding, `napi\_check\_object\_type\_tag()` can be used along with the original type tag to determine whether the JavaScript object was previously "marked" with the type tag. This creates a type-checking capability of a higher fidelity than `napi\_instanceof()` can provide, because such type- tagging survives prototype manipulation and addon unloading/reloading. Continuing the above example, the following skeleton addon implementation illustrates the use of `napi\_type\_tag\_object()` and `napi\_check\_object\_type\_tag()`. ```c // This value is the type tag for a database handle. The command // // uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.\*)/0x\1, 0x\2/' // // can be used to obtain the two values with which to initialize the structure. static const napi\_type\_tag DatabaseHandleTypeTag = { 0x1edf75a38336451d, 0xa5ed9ce2e4c00c38 }; // This value is the type tag for a query handle. static const napi\_type\_tag QueryHandleTypeTag = { 0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a }; static napi\_value openDatabase(napi\_env env, napi\_callback\_info info) { napi\_status status; napi\_value result; // Perform the underlying action which results in a database handle. DatabaseHandle\* dbHandle = open\_database(); // Create a new, empty JS object. status = napi\_create\_object(env, &result); if (status != napi\_ok) return NULL; // Tag the object to indicate that it holds a pointer to a `DatabaseHandle`. status = napi\_type\_tag\_object(env, result, &DatabaseHandleTypeTag); if (status != napi\_ok) return NULL; // Store the pointer to the `DatabaseHandle` structure inside the JS object. status = napi\_wrap(env, result, dbHandle, NULL, NULL, NULL); if (status != napi\_ok) return NULL; return result; } // Later when we receive a JavaScript object purporting to be a database handle // we can use `napi\_check\_object\_type\_tag()` to ensure that it is indeed such a // handle. static napi\_value query(napi\_env env, napi\_callback\_info info) { napi\_status status; size\_t argc = 2; napi\_value argv[2]; bool is\_db\_handle; status = napi\_get\_cb\_info(env, info, &argc, argv, NULL, NULL); if (status != napi\_ok) return NULL; // Check that the object passed as the first parameter has the previously // applied tag. status = napi\_check\_object\_type\_tag(env, argv[0], &DatabaseHandleTypeTag, &is\_db\_handle); if (status != napi\_ok) return NULL; // Throw a `TypeError` if it doesn't. if (!is\_db\_handle) { // Throw a TypeError. return NULL; } } ``` ### `napi\_define\_class` ```c napi\_status napi\_define\_class(napi\_env env, const char\* utf8name, size\_t length, napi\_callback constructor, void\* data, size\_t property\_count, const napi\_property\_descriptor\* properties, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] utf8name`: Name of the JavaScript constructor function. For clarity, it is recommended to use the C++ class name when wrapping a C++ class. \* `[in] length`: The length of the `utf8name` in bytes, or `NAPI\_AUTO\_LENGTH` if it is null-terminated. \* `[in] constructor`: Callback function that handles constructing instances of the class. When wrapping a C++ class, this method must be a static member with the [`napi\_callback`][] signature. A C++ class constructor cannot be used. [`napi\_callback`][] provides more details. \* `[in] data`: Optional data to be passed to the constructor callback as the `data` property of the callback info. \* | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.07606640458106995,
0.023739034309983253,
0.012981213629245758,
0.11846797913312912,
-0.00748168071731925,
-0.0330561101436615,
0.07993026077747345,
0.014999622479081154,
0.045760948210954666,
-0.07069501280784607,
-0.07664678245782852,
0.007052074186503887,
0.00007122609531506896,
-0.01... | 0.191846 |
the class. When wrapping a C++ class, this method must be a static member with the [`napi\_callback`][] signature. A C++ class constructor cannot be used. [`napi\_callback`][] provides more details. \* `[in] data`: Optional data to be passed to the constructor callback as the `data` property of the callback info. \* `[in] property\_count`: Number of items in the `properties` array argument. \* `[in] properties`: Array of property descriptors describing static and instance data properties, accessors, and methods on the class See `napi\_property\_descriptor`. \* `[out] result`: A `napi\_value` representing the constructor function for the class. Returns `napi\_ok` if the API succeeded. Defines a JavaScript class, including: \* A JavaScript constructor function that has the class name. When wrapping a corresponding C++ class, the callback passed via `constructor` can be used to instantiate a new C++ class instance, which can then be placed inside the JavaScript object instance being constructed using [`napi\_wrap`][]. \* Properties on the constructor function whose implementation can call corresponding \_static\_ data properties, accessors, and methods of the C++ class (defined by property descriptors with the `napi\_static` attribute). \* Properties on the constructor function's `prototype` object. When wrapping a C++ class, \_non-static\_ data properties, accessors, and methods of the C++ class can be called from the static functions given in the property descriptors without the `napi\_static` attribute after retrieving the C++ class instance placed inside the JavaScript object instance by using [`napi\_unwrap`][]. When wrapping a C++ class, the C++ constructor callback passed via `constructor` should be a static method on the class that calls the actual class constructor, then wraps the new C++ instance in a JavaScript object, and returns the wrapper object. See [`napi\_wrap`][] for details. The JavaScript constructor function returned from [`napi\_define\_class`][] is often saved and used later to construct new instances of the class from native code, and/or to check whether provided values are instances of the class. In that case, to prevent the function value from being garbage-collected, a strong persistent reference to it can be created using [`napi\_create\_reference`][], ensuring that the reference count is kept >= 1. Any non-`NULL` data which is passed to this API via the `data` parameter or via the `data` field of the `napi\_property\_descriptor` array items can be associated with the resulting JavaScript constructor (which is returned in the `result` parameter) and freed whenever the class is garbage-collected by passing both the JavaScript function and the data to [`napi\_add\_finalizer`][]. ### `napi\_wrap` ```c napi\_status napi\_wrap(napi\_env env, napi\_value js\_object, void\* native\_object, napi\_finalize finalize\_cb, void\* finalize\_hint, napi\_ref\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] js\_object`: The JavaScript object that will be the wrapper for the native object. \* `[in] native\_object`: The native instance that will be wrapped in the JavaScript object. \* `[in] finalize\_cb`: Optional native callback that can be used to free the native instance when the JavaScript object has been garbage-collected. [`napi\_finalize`][] provides more details. \* `[in] finalize\_hint`: Optional contextual hint that is passed to the finalize callback. \* `[out] result`: Optional reference to the wrapped object. Returns `napi\_ok` if the API succeeded. Wraps a native instance in a JavaScript object. The native instance can be retrieved later using `napi\_unwrap()`. When JavaScript code invokes a constructor for a class that was defined using `napi\_define\_class()`, the `napi\_callback` for the constructor is invoked. After constructing an instance of the native class, the callback must then call `napi\_wrap()` to wrap the newly constructed instance in the already-created JavaScript object that is the `this` argument to the constructor callback. (That `this` object was created from the constructor function's `prototype`, so it already has definitions of all the instance | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.09719420224428177,
0.10890066623687744,
-0.04663390293717384,
0.07165279984474182,
-0.08455660194158554,
-0.011282979510724545,
0.05396927893161774,
0.003265895415097475,
-0.010656730271875858,
-0.07299116998910904,
0.011649915017187595,
0.007313001900911331,
-0.007687282282859087,
-0.0... | 0.149569 |
instance of the native class, the callback must then call `napi\_wrap()` to wrap the newly constructed instance in the already-created JavaScript object that is the `this` argument to the constructor callback. (That `this` object was created from the constructor function's `prototype`, so it already has definitions of all the instance properties and methods.) Typically when wrapping a class instance, a finalize callback should be provided that simply deletes the native instance that is received as the `data` argument to the finalize callback. The optional returned reference is initially a weak reference, meaning it has a reference count of 0. Typically this reference count would be incremented temporarily during async operations that require the instance to remain valid. \_Caution\_: The optional returned reference (if obtained) should be deleted via [`napi\_delete\_reference`][] ONLY in response to the finalize callback invocation. If it is deleted before then, then the finalize callback may never be invoked. Therefore, when obtaining a reference a finalize callback is also required in order to enable correct disposal of the reference. Finalizer callbacks may be deferred, leaving a window where the object has been garbage collected (and the weak reference is invalid) but the finalizer hasn't been called yet. When using `napi\_get\_reference\_value()` on weak references returned by `napi\_wrap()`, you should still handle an empty result. Calling `napi\_wrap()` a second time on an object will return an error. To associate another native instance with the object, use `napi\_remove\_wrap()` first. ### `napi\_unwrap` ```c napi\_status napi\_unwrap(napi\_env env, napi\_value js\_object, void\*\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] js\_object`: The object associated with the native instance. \* `[out] result`: Pointer to the wrapped native instance. Returns `napi\_ok` if the API succeeded. Retrieves a native instance that was previously wrapped in a JavaScript object using `napi\_wrap()`. When JavaScript code invokes a method or property accessor on the class, the corresponding `napi\_callback` is invoked. If the callback is for an instance method or accessor, then the `this` argument to the callback is the wrapper object; the wrapped C++ instance that is the target of the call can be obtained then by calling `napi\_unwrap()` on the wrapper object. ### `napi\_remove\_wrap` ```c napi\_status napi\_remove\_wrap(napi\_env env, napi\_value js\_object, void\*\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] js\_object`: The object associated with the native instance. \* `[out] result`: Pointer to the wrapped native instance. Returns `napi\_ok` if the API succeeded. Retrieves a native instance that was previously wrapped in the JavaScript object `js\_object` using `napi\_wrap()` and removes the wrapping. If a finalize callback was associated with the wrapping, it will no longer be called when the JavaScript object becomes garbage-collected. ### `napi\_type\_tag\_object` ```c napi\_status napi\_type\_tag\_object(napi\_env env, napi\_value js\_object, const napi\_type\_tag\* type\_tag); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] js\_object`: The JavaScript object or [external][] to be marked. \* `[in] type\_tag`: The tag with which the object is to be marked. Returns `napi\_ok` if the API succeeded. Associates the value of the `type\_tag` pointer with the JavaScript object or [external][]. `napi\_check\_object\_type\_tag()` can then be used to compare the tag that was attached to the object with one owned by the addon to ensure that the object has the right type. If the object already has an associated type tag, this API will return `napi\_invalid\_arg`. ### `napi\_check\_object\_type\_tag` ```c napi\_status napi\_check\_object\_type\_tag(napi\_env env, napi\_value js\_object, const napi\_type\_tag\* type\_tag, bool\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] js\_object`: The JavaScript object or [external][] whose type tag to examine. \* `[in] type\_tag`: The tag with | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.10245900601148605,
0.044830307364463806,
0.011940197087824345,
0.04966483265161514,
0.02671017497777939,
-0.032622553408145905,
0.06496245414018631,
-0.017237866297364235,
0.04899591952562332,
-0.059684548527002335,
0.016622763127088547,
0.0336998775601387,
-0.0797232985496521,
-0.02237... | 0.124344 |
tag, this API will return `napi\_invalid\_arg`. ### `napi\_check\_object\_type\_tag` ```c napi\_status napi\_check\_object\_type\_tag(napi\_env env, napi\_value js\_object, const napi\_type\_tag\* type\_tag, bool\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] js\_object`: The JavaScript object or [external][] whose type tag to examine. \* `[in] type\_tag`: The tag with which to compare any tag found on the object. \* `[out] result`: Whether the type tag given matched the type tag on the object. `false` is also returned if no type tag was found on the object. Returns `napi\_ok` if the API succeeded. Compares the pointer given as `type\_tag` with any that can be found on `js\_object`. If no tag is found on `js\_object` or, if a tag is found but it does not match `type\_tag`, then `result` is set to `false`. If a tag is found and it matches `type\_tag`, then `result` is set to `true`. ### `napi\_add\_finalizer` ```c napi\_status napi\_add\_finalizer(napi\_env env, napi\_value js\_object, void\* finalize\_data, node\_api\_basic\_finalize finalize\_cb, void\* finalize\_hint, napi\_ref\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] js\_object`: The JavaScript object to which the native data will be attached. \* `[in] finalize\_data`: Optional data to be passed to `finalize\_cb`. \* `[in] finalize\_cb`: Native callback that will be used to free the native data when the JavaScript object has been garbage-collected. [`napi\_finalize`][] provides more details. \* `[in] finalize\_hint`: Optional contextual hint that is passed to the finalize callback. \* `[out] result`: Optional reference to the JavaScript object. Returns `napi\_ok` if the API succeeded. Adds a `napi\_finalize` callback which will be called when the JavaScript object in `js\_object` has been garbage-collected. This API can be called multiple times on a single JavaScript object. \_Caution\_: The optional returned reference (if obtained) should be deleted via [`napi\_delete\_reference`][] ONLY in response to the finalize callback invocation. If it is deleted before then, then the finalize callback may never be invoked. Therefore, when obtaining a reference a finalize callback is also required in order to enable correct disposal of the reference. #### `node\_api\_post\_finalizer` > Stability: 1 - Experimental ```c napi\_status node\_api\_post\_finalizer(node\_api\_basic\_env env, napi\_finalize finalize\_cb, void\* finalize\_data, void\* finalize\_hint); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] finalize\_cb`: Native callback that will be used to free the native data when the JavaScript object has been garbage-collected. [`napi\_finalize`][] provides more details. \* `[in] finalize\_data`: Optional data to be passed to `finalize\_cb`. \* `[in] finalize\_hint`: Optional contextual hint that is passed to the finalize callback. Returns `napi\_ok` if the API succeeded. Schedules a `napi\_finalize` callback to be called asynchronously in the event loop. Normally, finalizers are called while the GC (garbage collector) collects objects. At that point calling any Node-API that may cause changes in the GC state will be disabled and will crash Node.js. `node\_api\_post\_finalizer` helps to work around this limitation by allowing the add-on to defer calls to such Node-APIs to a point in time outside of the GC finalization. ## Simple asynchronous operations Addon modules often need to leverage async helpers from libuv as part of their implementation. This allows them to schedule work to be executed asynchronously so that their methods can return in advance of the work being completed. This allows them to avoid blocking overall execution of the Node.js application. Node-API provides an ABI-stable interface for these supporting functions which covers the most common asynchronous use cases. Node-API defines the `napi\_async\_work` structure which is used to manage asynchronous workers. Instances are created/deleted with [`napi\_create\_async\_work`][] and [`napi\_delete\_async\_work`][]. The `execute` and `complete` callbacks are functions that will be invoked when the executor is ready to execute and when it | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.06345817446708679,
0.10069551318883896,
-0.023063359782099724,
0.027225328609347343,
0.04237726703286171,
-0.0838681161403656,
0.07573691755533218,
0.025947220623493195,
-0.01299439650028944,
-0.08494611084461212,
-0.0658479779958725,
-0.04461243748664856,
-0.03412964940071106,
0.056717... | 0.232223 |
supporting functions which covers the most common asynchronous use cases. Node-API defines the `napi\_async\_work` structure which is used to manage asynchronous workers. Instances are created/deleted with [`napi\_create\_async\_work`][] and [`napi\_delete\_async\_work`][]. The `execute` and `complete` callbacks are functions that will be invoked when the executor is ready to execute and when it completes its task respectively. The `execute` function should avoid making any Node-API calls that could result in the execution of JavaScript or interaction with JavaScript objects. Most often, any code that needs to make Node-API calls should be made in `complete` callback instead. Avoid using the `napi\_env` parameter in the execute callback as it will likely execute JavaScript. These functions implement the following interfaces: ```c typedef void (\*napi\_async\_execute\_callback)(napi\_env env, void\* data); typedef void (\*napi\_async\_complete\_callback)(napi\_env env, napi\_status status, void\* data); ``` When these methods are invoked, the `data` parameter passed will be the addon-provided `void\*` data that was passed into the `napi\_create\_async\_work` call. Once created the async worker can be queued for execution using the [`napi\_queue\_async\_work`][] function: ```c napi\_status napi\_queue\_async\_work(node\_api\_basic\_env env, napi\_async\_work work); ``` [`napi\_cancel\_async\_work`][] can be used if the work needs to be cancelled before the work has started execution. After calling [`napi\_cancel\_async\_work`][], the `complete` callback will be invoked with a status value of `napi\_cancelled`. The work should not be deleted before the `complete` callback invocation, even when it was cancelled. ### `napi\_create\_async\_work` ```c napi\_status napi\_create\_async\_work(napi\_env env, napi\_value async\_resource, napi\_value async\_resource\_name, napi\_async\_execute\_callback execute, napi\_async\_complete\_callback complete, void\* data, napi\_async\_work\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] async\_resource`: An optional object associated with the async work that will be passed to possible `async\_hooks` [`init` hooks][]. \* `[in] async\_resource\_name`: Identifier for the kind of resource that is being provided for diagnostic information exposed by the `async\_hooks` API. \* `[in] execute`: The native function which should be called to execute the logic asynchronously. The given function is called from a worker pool thread and can execute in parallel with the main event loop thread. \* `[in] complete`: The native function which will be called when the asynchronous logic is completed or is cancelled. The given function is called from the main event loop thread. [`napi\_async\_complete\_callback`][] provides more details. \* `[in] data`: User-provided data context. This will be passed back into the execute and complete functions. \* `[out] result`: `napi\_async\_work\*` which is the handle to the newly created async work. Returns `napi\_ok` if the API succeeded. This API allocates a work object that is used to execute logic asynchronously. It should be freed using [`napi\_delete\_async\_work`][] once the work is no longer required. `async\_resource\_name` should be a null-terminated, UTF-8-encoded string. The `async\_resource\_name` identifier is provided by the user and should be representative of the type of async work being performed. It is also recommended to apply namespacing to the identifier, e.g. by including the module name. See the [`async\_hooks` documentation][async\_hooks `type`] for more information. ### `napi\_delete\_async\_work` ```c napi\_status napi\_delete\_async\_work(napi\_env env, napi\_async\_work work); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] work`: The handle returned by the call to `napi\_create\_async\_work`. Returns `napi\_ok` if the API succeeded. This API frees a previously allocated work object. This API can be called even if there is a pending JavaScript exception. ### `napi\_queue\_async\_work` ```c napi\_status napi\_queue\_async\_work(node\_api\_basic\_env env, napi\_async\_work work); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] work`: The handle returned by the call to `napi\_create\_async\_work`. Returns `napi\_ok` if the API succeeded. This API requests that the previously allocated work be scheduled for execution. Once it returns successfully, this API must not be called again with the same `napi\_async\_work` item or | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.10420350730419159,
0.05744636431336403,
-0.050270043313503265,
0.07739958167076111,
-0.000892437354195863,
-0.06256109476089478,
-0.08899902552366257,
-0.026359587907791138,
0.07818085700273514,
-0.04259300231933594,
-0.029631484299898148,
0.031076006591320038,
-0.0681285485625267,
-0.0... | 0.196825 |
API is invoked under. \* `[in] work`: The handle returned by the call to `napi\_create\_async\_work`. Returns `napi\_ok` if the API succeeded. This API requests that the previously allocated work be scheduled for execution. Once it returns successfully, this API must not be called again with the same `napi\_async\_work` item or the result will be undefined. ### `napi\_cancel\_async\_work` ```c napi\_status napi\_cancel\_async\_work(node\_api\_basic\_env env, napi\_async\_work work); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] work`: The handle returned by the call to `napi\_create\_async\_work`. Returns `napi\_ok` if the API succeeded. This API cancels queued work if it has not yet been started. If it has already started executing, it cannot be cancelled and `napi\_generic\_failure` will be returned. If successful, the `complete` callback will be invoked with a status value of `napi\_cancelled`. The work should not be deleted before the `complete` callback invocation, even if it has been successfully cancelled. This API can be called even if there is a pending JavaScript exception. ## Custom asynchronous operations The simple asynchronous work APIs above may not be appropriate for every scenario. When using any other asynchronous mechanism, the following APIs are necessary to ensure an asynchronous operation is properly tracked by the runtime. ### `napi\_async\_init` ```c napi\_status napi\_async\_init(napi\_env env, napi\_value async\_resource, napi\_value async\_resource\_name, napi\_async\_context\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] async\_resource`: Object associated with the async work that will be passed to possible `async\_hooks` [`init` hooks][] and can be accessed by [`async\_hooks.executionAsyncResource()`][]. \* `[in] async\_resource\_name`: Identifier for the kind of resource that is being provided for diagnostic information exposed by the `async\_hooks` API. \* `[out] result`: The initialized async context. Returns `napi\_ok` if the API succeeded. In order to retain ABI compatibility with previous versions, passing `NULL` for `async\_resource` does not result in an error. However, this is not recommended as this will result in undesirable behavior with `async\_hooks` [`init` hooks][] and `async\_hooks.executionAsyncResource()` as the resource is now required by the underlying `async\_hooks` implementation in order to provide the linkage between async callbacks. Previous versions of this API were not maintaining a strong reference to `async\_resource` while the `napi\_async\_context` object existed and instead expected the caller to hold a strong reference. This has been changed, as a corresponding call to [`napi\_async\_destroy`][] for every call to `napi\_async\_init()` is a requirement in any case to avoid memory leaks. ### `napi\_async\_destroy` ```c napi\_status napi\_async\_destroy(napi\_env env, napi\_async\_context async\_context); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] async\_context`: The async context to be destroyed. Returns `napi\_ok` if the API succeeded. This API can be called even if there is a pending JavaScript exception. ### `napi\_make\_callback` ```c NAPI\_EXTERN napi\_status napi\_make\_callback(napi\_env env, napi\_async\_context async\_context, napi\_value recv, napi\_value func, size\_t argc, const napi\_value\* argv, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] async\_context`: Context for the async operation that is invoking the callback. This should normally be a value previously obtained from [`napi\_async\_init`][]. In order to retain ABI compatibility with previous versions, passing `NULL` for `async\_context` does not result in an error. However, this results in incorrect operation of async hooks. Potential issues include loss of async context when using the `AsyncLocalStorage` API. \* `[in] recv`: The `this` value passed to the called function. \* `[in] func`: `napi\_value` representing the JavaScript function to be invoked. \* `[in] argc`: The count of elements in the `argv` array. \* `[in] argv`: Array of JavaScript values as `napi\_value` representing the arguments to the function. If `argc` is zero this parameter may be omitted by passing in `NULL`. \* | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.11583524197340012,
0.07726488262414932,
-0.08245030045509338,
0.06944692134857178,
-0.015833748504519463,
-0.08552692085504532,
-0.006974546704441309,
-0.08708622306585312,
0.07883114367723465,
-0.03668205440044403,
-0.011968831531703472,
0.026052342727780342,
-0.031114455312490463,
-0.... | 0.205705 |
`[in] func`: `napi\_value` representing the JavaScript function to be invoked. \* `[in] argc`: The count of elements in the `argv` array. \* `[in] argv`: Array of JavaScript values as `napi\_value` representing the arguments to the function. If `argc` is zero this parameter may be omitted by passing in `NULL`. \* `[out] result`: `napi\_value` representing the JavaScript object returned. Returns `napi\_ok` if the API succeeded. This method allows a JavaScript function object to be called from a native add-on. This API is similar to `napi\_call\_function`. However, it is used to call \_from\_ native code back \_into\_ JavaScript \_after\_ returning from an async operation (when there is no other script on the stack). It is a fairly simple wrapper around `node::MakeCallback`. Note it is \_not\_ necessary to use `napi\_make\_callback` from within a `napi\_async\_complete\_callback`; in that situation the callback's async context has already been set up, so a direct call to `napi\_call\_function` is sufficient and appropriate. Use of the `napi\_make\_callback` function may be required when implementing custom async behavior that does not use `napi\_create\_async\_work`. Any `process.nextTick`s or Promises scheduled on the microtask queue by JavaScript during the callback are ran before returning back to C/C++. ### `napi\_open\_callback\_scope` ```c NAPI\_EXTERN napi\_status napi\_open\_callback\_scope(napi\_env env, napi\_value resource\_object, napi\_async\_context context, napi\_callback\_scope\* result) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] resource\_object`: An object associated with the async work that will be passed to possible `async\_hooks` [`init` hooks][]. This parameter has been deprecated and is ignored at runtime. Use the `async\_resource` parameter in [`napi\_async\_init`][] instead. \* `[in] context`: Context for the async operation that is invoking the callback. This should be a value previously obtained from [`napi\_async\_init`][]. \* `[out] result`: The newly created scope. There are cases (for example, resolving promises) where it is necessary to have the equivalent of the scope associated with a callback in place when making certain Node-API calls. If there is no other script on the stack the [`napi\_open\_callback\_scope`][] and [`napi\_close\_callback\_scope`][] functions can be used to open/close the required scope. ### `napi\_close\_callback\_scope` ```c NAPI\_EXTERN napi\_status napi\_close\_callback\_scope(napi\_env env, napi\_callback\_scope scope) ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] scope`: The scope to be closed. This API can be called even if there is a pending JavaScript exception. ## Version management ### `napi\_get\_node\_version` ```c typedef struct { uint32\_t major; uint32\_t minor; uint32\_t patch; const char\* release; } napi\_node\_version; napi\_status napi\_get\_node\_version(node\_api\_basic\_env env, const napi\_node\_version\*\* version); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] version`: A pointer to version information for Node.js itself. Returns `napi\_ok` if the API succeeded. This function fills the `version` struct with the major, minor, and patch version of Node.js that is currently running, and the `release` field with the value of [`process.release.name`][`process.release`]. The returned buffer is statically allocated and does not need to be freed. ### `napi\_get\_version` ```c napi\_status napi\_get\_version(node\_api\_basic\_env env, uint32\_t\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: The highest version of Node-API supported. Returns `napi\_ok` if the API succeeded. This API returns the highest Node-API version supported by the Node.js runtime. Node-API is planned to be additive such that newer releases of Node.js may support additional API functions. In order to allow an addon to use a newer function when running with versions of Node.js that support it, while providing fallback behavior when running with Node.js versions that don't support it: \* Call `napi\_get\_version()` to determine if the API is available. \* If available, dynamically load a pointer to the function using `uv\_dlsym()`. \* Use the dynamically loaded pointer to invoke the function. | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.10668714344501495,
0.05267665535211563,
-0.07754398882389069,
0.11100489646196365,
-0.025699298828840256,
-0.05697985738515854,
0.06257471442222595,
-0.014657541178166866,
0.020364968106150627,
-0.09410257637500763,
-0.037718258798122406,
-0.0326436348259449,
-0.04045679420232773,
-0.05... | 0.173333 |
of Node.js that support it, while providing fallback behavior when running with Node.js versions that don't support it: \* Call `napi\_get\_version()` to determine if the API is available. \* If available, dynamically load a pointer to the function using `uv\_dlsym()`. \* Use the dynamically loaded pointer to invoke the function. \* If the function is not available, provide an alternate implementation that does not use the function. ## Memory management ### `napi\_adjust\_external\_memory` ```c NAPI\_EXTERN napi\_status napi\_adjust\_external\_memory(node\_api\_basic\_env env, int64\_t change\_in\_bytes, int64\_t\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] change\_in\_bytes`: The change in externally allocated memory that is kept alive by JavaScript objects. \* `[out] result`: The adjusted value. This value should reflect the total amount of external memory with the given `change\_in\_bytes` included. The absolute value of the returned value should not be depended on. For example, implementations may use a single counter for all addons, or a counter for each addon. Returns `napi\_ok` if the API succeeded. This function gives the runtime 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 addon). Registering externally allocated memory may, but is not guaranteed to, trigger global garbage collections more often than it would otherwise. This function is expected to be called in a manner such that an addon does not decrease the external memory more than it has increased the external memory. ## Promises Node-API provides facilities for creating `Promise` objects as described in [Section Promise objects][] of the ECMA specification. It implements promises as a pair of objects. When a promise is created by `napi\_create\_promise()`, a "deferred" object is created and returned alongside the `Promise`. The deferred object is bound to the created `Promise` and is the only means to resolve or reject the `Promise` using `napi\_resolve\_deferred()` or `napi\_reject\_deferred()`. The deferred object that is created by `napi\_create\_promise()` is freed by `napi\_resolve\_deferred()` or `napi\_reject\_deferred()`. The `Promise` object may be returned to JavaScript where it can be used in the usual fashion. For example, to create a promise and pass it to an asynchronous worker: ```c napi\_deferred deferred; napi\_value promise; napi\_status status; // Create the promise. status = napi\_create\_promise(env, &deferred, &promise); if (status != napi\_ok) return NULL; // Pass the deferred to a function that performs an asynchronous action. do\_something\_asynchronous(deferred); // Return the promise to JS return promise; ``` The above function `do\_something\_asynchronous()` would perform its asynchronous action and then it would resolve or reject the deferred, thereby concluding the promise and freeing the deferred: ```c napi\_deferred deferred; napi\_value undefined; napi\_status status; // Create a value with which to conclude the deferred. status = napi\_get\_undefined(env, &undefined); if (status != napi\_ok) return NULL; // Resolve or reject the promise associated with the deferred depending on // whether the asynchronous action succeeded. if (asynchronous\_action\_succeeded) { status = napi\_resolve\_deferred(env, deferred, undefined); } else { status = napi\_reject\_deferred(env, deferred, undefined); } if (status != napi\_ok) return NULL; // At this point the deferred has been freed, so we should assign NULL to it. deferred = NULL; ``` ### `napi\_create\_promise` ```c napi\_status napi\_create\_promise(napi\_env env, napi\_deferred\* deferred, napi\_value\* promise); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] deferred`: A newly created deferred object which can later be passed to `napi\_resolve\_deferred()` or `napi\_reject\_deferred()` to resolve resp. reject the associated promise. \* `[out] promise`: The JavaScript promise associated with the deferred object. Returns `napi\_ok` if the API succeeded. This API creates a deferred object and a JavaScript promise. ### `napi\_resolve\_deferred` ```c napi\_status napi\_resolve\_deferred(napi\_env env, napi\_deferred deferred, | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.047771185636520386,
0.05721885338425636,
-0.005271944683045149,
0.06494611501693726,
0.03372751921415329,
-0.0274832621216774,
-0.04751790687441826,
0.06182298809289932,
-0.009456465020775795,
-0.03132406622171402,
-0.02530474029481411,
0.042318783700466156,
-0.030715638771653175,
-0.01... | 0.159867 |
can later be passed to `napi\_resolve\_deferred()` or `napi\_reject\_deferred()` to resolve resp. reject the associated promise. \* `[out] promise`: The JavaScript promise associated with the deferred object. Returns `napi\_ok` if the API succeeded. This API creates a deferred object and a JavaScript promise. ### `napi\_resolve\_deferred` ```c napi\_status napi\_resolve\_deferred(napi\_env env, napi\_deferred deferred, napi\_value resolution); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] deferred`: The deferred object whose associated promise to resolve. \* `[in] resolution`: The value with which to resolve the promise. This API resolves a JavaScript promise by way of the deferred object with which it is associated. Thus, it can only be used to resolve JavaScript promises for which the corresponding deferred object is available. This effectively means that the promise must have been created using `napi\_create\_promise()` and the deferred object returned from that call must have been retained in order to be passed to this API. The deferred object is freed upon successful completion. ### `napi\_reject\_deferred` ```c napi\_status napi\_reject\_deferred(napi\_env env, napi\_deferred deferred, napi\_value rejection); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] deferred`: The deferred object whose associated promise to resolve. \* `[in] rejection`: The value with which to reject the promise. This API rejects a JavaScript promise by way of the deferred object with which it is associated. Thus, it can only be used to reject JavaScript promises for which the corresponding deferred object is available. This effectively means that the promise must have been created using `napi\_create\_promise()` and the deferred object returned from that call must have been retained in order to be passed to this API. The deferred object is freed upon successful completion. ### `napi\_is\_promise` ```c napi\_status napi\_is\_promise(napi\_env env, napi\_value value, bool\* is\_promise); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] value`: The value to examine \* `[out] is\_promise`: Flag indicating whether `promise` is a native promise object (that is, a promise object created by the underlying engine). ## Script execution Node-API provides an API for executing a string containing JavaScript using the underlying JavaScript engine. ### `napi\_run\_script` ```c NAPI\_EXTERN napi\_status napi\_run\_script(napi\_env env, napi\_value script, napi\_value\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] script`: A JavaScript string containing the script to execute. \* `[out] result`: The value resulting from having executed the script. 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 using `let` and `const` will be visible globally, but will not be added to the [`global`][] object. \* The value of `this` is [`global`][] within the script. ## libuv event loop Node-API provides a function for getting the current event loop associated with a specific `napi\_env`. ### `napi\_get\_uv\_event\_loop` ```c NAPI\_EXTERN napi\_status napi\_get\_uv\_event\_loop(node\_api\_basic\_env env, struct uv\_loop\_s\*\* loop); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] loop`: The current libuv loop instance. Note: While libuv has been relatively stable over time, it does not provide an ABI stability guarantee. Use of this function should be avoided. Its use may result in an addon that does not work across Node.js versions. [asynchronous-thread-safe-function-calls](https://nodejs.org/docs/latest/api/n-api.html#asynchronous-thread-safe-function-calls) are an alternative for many use cases. ## Asynchronous thread-safe function calls JavaScript | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.15766587853431702,
0.09301751852035522,
0.02630520798265934,
0.018948765471577644,
-0.03103070706129074,
-0.03384416550397873,
-0.012589747086167336,
-0.012809572741389275,
0.07769542932510376,
-0.0660543367266655,
-0.03326302021741867,
0.040088605135679245,
0.0063504064455628395,
0.004... | 0.180746 |
libuv has been relatively stable over time, it does not provide an ABI stability guarantee. Use of this function should be avoided. Its use may result in an addon that does not work across Node.js versions. [asynchronous-thread-safe-function-calls](https://nodejs.org/docs/latest/api/n-api.html#asynchronous-thread-safe-function-calls) are an alternative for many use cases. ## Asynchronous thread-safe function calls JavaScript functions can normally only be called from a native addon's main thread. If an addon creates additional threads, then Node-API functions that require a `napi\_env`, `napi\_value`, or `napi\_ref` must not be called from those threads. When an addon has additional threads and JavaScript functions need to be invoked based on the processing completed by those threads, those threads must communicate with the addon's main thread so that the main thread can invoke the JavaScript function on their behalf. The thread-safe function APIs provide an easy way to do this. These APIs provide the type `napi\_threadsafe\_function` as well as APIs to create, destroy, and call objects of this type. `napi\_create\_threadsafe\_function()` creates a persistent reference to a `napi\_value` that holds a JavaScript function which can be called from multiple threads. The calls happen asynchronously. This means that values with which the JavaScript callback is to be called will be placed in a queue, and, for each value in the queue, a call will eventually be made to the JavaScript function. Upon creation of a `napi\_threadsafe\_function` a `napi\_finalize` callback can be provided. This callback will be invoked on the main thread when the thread-safe function is about to be destroyed. It receives the context and the finalize data given during construction, and provides an opportunity for cleaning up after the threads e.g. by calling `uv\_thread\_join()`. \*\*Aside from the main loop thread, no threads should be using the thread-safe function after the finalize callback completes.\*\* The `context` given during the call to `napi\_create\_threadsafe\_function()` can be retrieved from any thread with a call to `napi\_get\_threadsafe\_function\_context()`. ### Calling a thread-safe function `napi\_call\_threadsafe\_function()` can be used for initiating a call into JavaScript. `napi\_call\_threadsafe\_function()` accepts a parameter which controls whether the API behaves blockingly. If set to `napi\_tsfn\_nonblocking`, the API behaves non-blockingly, returning `napi\_queue\_full` if the queue was full, preventing data from being successfully added to the queue. If set to `napi\_tsfn\_blocking`, the API blocks until space becomes available in the queue. `napi\_call\_threadsafe\_function()` never blocks if the thread-safe function was created with a maximum queue size of 0. `napi\_call\_threadsafe\_function()` should not be called with `napi\_tsfn\_blocking` from a JavaScript thread, because, if the queue is full, it may cause the JavaScript thread to deadlock. The actual call into JavaScript is controlled by the callback given via the `call\_js\_cb` parameter. `call\_js\_cb` is invoked on the main thread once for each value that was placed into the queue by a successful call to `napi\_call\_threadsafe\_function()`. If such a callback is not given, a default callback will be used, and the resulting JavaScript call will have no arguments. The `call\_js\_cb` callback receives the JavaScript function to call as a `napi\_value` in its parameters, as well as the `void\*` context pointer used when creating the `napi\_threadsafe\_function`, and the next data pointer that was created by one of the secondary threads. The callback can then use an API such as `napi\_call\_function()` to call into JavaScript. The callback may also be invoked with `env` and `call\_js\_cb` both set to `NULL` to indicate that calls into JavaScript are no longer possible, while items remain in the queue that may need to be freed. This normally occurs when the Node.js process exits while there is a thread-safe function still active. It is not necessary to call into JavaScript via `napi\_make\_callback()` because Node-API runs `call\_js\_cb` in a context appropriate | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.11951197683811188,
-0.05435853824019432,
0.0016542782541364431,
0.01720684953033924,
0.06034720689058304,
-0.02361915074288845,
-0.05699015036225319,
-0.03587529808282852,
0.04266444593667984,
-0.03803245723247528,
-0.056540317833423615,
0.04197420924901962,
-0.05177551880478859,
-0.065... | 0.073929 |
are no longer possible, while items remain in the queue that may need to be freed. This normally occurs when the Node.js process exits while there is a thread-safe function still active. It is not necessary to call into JavaScript via `napi\_make\_callback()` because Node-API runs `call\_js\_cb` in a context appropriate for callbacks. Zero or more queued items may be invoked in each tick of the event loop. Applications should not depend on a specific behavior other than progress in invoking callbacks will be made and events will be invoked as time moves forward. ### Reference counting of thread-safe functions Threads can be added to and removed from a `napi\_threadsafe\_function` object during its existence. Thus, in addition to specifying an initial number of threads upon creation, `napi\_acquire\_threadsafe\_function` can be called to indicate that a new thread will start making use of the thread-safe function. Similarly, `napi\_release\_threadsafe\_function` can be called to indicate that an existing thread will stop making use of the thread-safe function. `napi\_threadsafe\_function` objects are destroyed when every thread which uses the object has called `napi\_release\_threadsafe\_function()` or has received a return status of `napi\_closing` in response to a call to `napi\_call\_threadsafe\_function`. The queue is emptied before the `napi\_threadsafe\_function` is destroyed. `napi\_release\_threadsafe\_function()` should be the last API call made in conjunction with a given `napi\_threadsafe\_function`, because after the call completes, there is no guarantee that the `napi\_threadsafe\_function` is still allocated. For the same reason, do not use a thread-safe function after receiving a return value of `napi\_closing` in response to a call to `napi\_call\_threadsafe\_function`. Data associated with the `napi\_threadsafe\_function` can be freed in its `napi\_finalize` callback which was passed to `napi\_create\_threadsafe\_function()`. The parameter `initial\_thread\_count` of `napi\_create\_threadsafe\_function` marks the initial number of acquisitions of the thread-safe functions, instead of calling `napi\_acquire\_threadsafe\_function` multiple times at creation. Once the number of threads making use of a `napi\_threadsafe\_function` reaches zero, no further threads can start making use of it by calling `napi\_acquire\_threadsafe\_function()`. In fact, all subsequent API calls associated with it, except `napi\_release\_threadsafe\_function()`, will return an error value of `napi\_closing`. The thread-safe function can be "aborted" by giving a value of `napi\_tsfn\_abort` to `napi\_release\_threadsafe\_function()`. This will cause all subsequent APIs associated with the thread-safe function except `napi\_release\_threadsafe\_function()` to return `napi\_closing` even before its reference count reaches zero. In particular, `napi\_call\_threadsafe\_function()` will return `napi\_closing`, thus informing the threads that it is no longer possible to make asynchronous calls to the thread-safe function. This can be used as a criterion for terminating the thread. \*\*Upon receiving a return value of `napi\_closing` from `napi\_call\_threadsafe\_function()` a thread must not use the thread-safe function anymore because it is no longer guaranteed to be allocated.\*\* ### Deciding whether to keep the process running Similarly to libuv handles, thread-safe functions can be "referenced" and "unreferenced". A "referenced" thread-safe function will cause the event loop on the thread on which it is created to remain alive until the thread-safe function is destroyed. In contrast, an "unreferenced" thread-safe function will not prevent the event loop from exiting. The APIs `napi\_ref\_threadsafe\_function` and `napi\_unref\_threadsafe\_function` exist for this purpose. Neither does `napi\_unref\_threadsafe\_function` mark the thread-safe functions as able to be destroyed nor does `napi\_ref\_threadsafe\_function` prevent it from being destroyed. ### `napi\_create\_threadsafe\_function` ```c NAPI\_EXTERN napi\_status napi\_create\_threadsafe\_function(napi\_env env, napi\_value func, napi\_value async\_resource, napi\_value async\_resource\_name, size\_t max\_queue\_size, size\_t initial\_thread\_count, void\* thread\_finalize\_data, napi\_finalize thread\_finalize\_cb, void\* context, napi\_threadsafe\_function\_call\_js call\_js\_cb, napi\_threadsafe\_function\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] func`: An optional JavaScript function to call from another thread. It must be provided if `NULL` is passed to `call\_js\_cb`. \* `[in] async\_resource`: An optional object associated with the async work that will be passed to possible | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.1094871386885643,
0.0018325929995626211,
-0.051220882683992386,
0.05951390415430069,
0.004192919470369816,
-0.008222565054893494,
0.024626504629850388,
-0.07696754485368729,
0.11982984095811844,
-0.023443561047315598,
-0.04138697683811188,
0.07165170460939407,
0.00046506489161401987,
-0... | 0.193139 |
\* `[in] env`: The environment that the API is invoked under. \* `[in] func`: An optional JavaScript function to call from another thread. It must be provided if `NULL` is passed to `call\_js\_cb`. \* `[in] async\_resource`: An optional object associated with the async work that will be passed to possible `async\_hooks` [`init` hooks][]. \* `[in] async\_resource\_name`: A JavaScript string to provide an identifier for the kind of resource that is being provided for diagnostic information exposed by the `async\_hooks` API. \* `[in] max\_queue\_size`: Maximum size of the queue. `0` for no limit. \* `[in] initial\_thread\_count`: The initial number of acquisitions, i.e. the initial number of threads, including the main thread, which will be making use of this function. \* `[in] thread\_finalize\_data`: Optional data to be passed to `thread\_finalize\_cb`. \* `[in] thread\_finalize\_cb`: Optional function to call when the `napi\_threadsafe\_function` is being destroyed. \* `[in] context`: Optional data to attach to the resulting `napi\_threadsafe\_function`. \* `[in] call\_js\_cb`: Optional callback which calls the JavaScript function in response to a call on a different thread. This callback will be called on the main thread. If not given, the JavaScript function will be called with no parameters and with `undefined` as its `this` value. [`napi\_threadsafe\_function\_call\_js`][] provides more details. \* `[out] result`: The asynchronous thread-safe JavaScript function. \*\*Change History:\*\* \* Version 10 (`NAPI\_VERSION` is defined as `10` or higher): Uncaught exceptions thrown in `call\_js\_cb` are handled with the [`'uncaughtException'`][] event, instead of being ignored. ### `napi\_get\_threadsafe\_function\_context` ```c NAPI\_EXTERN napi\_status napi\_get\_threadsafe\_function\_context(napi\_threadsafe\_function func, void\*\* result); ``` \* `[in] func`: The thread-safe function for which to retrieve the context. \* `[out] result`: The location where to store the context. This API may be called from any thread which makes use of `func`. ### `napi\_call\_threadsafe\_function` ```c NAPI\_EXTERN napi\_status napi\_call\_threadsafe\_function(napi\_threadsafe\_function func, void\* data, napi\_threadsafe\_function\_call\_mode is\_blocking); ``` \* `[in] func`: The asynchronous thread-safe JavaScript function to invoke. \* `[in] data`: Data to send into JavaScript via the callback `call\_js\_cb` provided during the creation of the thread-safe JavaScript function. \* `[in] is\_blocking`: Flag whose value can be either `napi\_tsfn\_blocking` to indicate that the call should block if the queue is full or `napi\_tsfn\_nonblocking` to indicate that the call should return immediately with a status of `napi\_queue\_full` whenever the queue is full. This API should not be called with `napi\_tsfn\_blocking` from a JavaScript thread, because, if the queue is full, it may cause the JavaScript thread to deadlock. This API will return `napi\_closing` if `napi\_release\_threadsafe\_function()` was called with `abort` set to `napi\_tsfn\_abort` from any thread. The value is only added to the queue if the API returns `napi\_ok`. This API may be called from any thread which makes use of `func`. ### `napi\_acquire\_threadsafe\_function` ```c NAPI\_EXTERN napi\_status napi\_acquire\_threadsafe\_function(napi\_threadsafe\_function func); ``` \* `[in] func`: The asynchronous thread-safe JavaScript function to start making use of. A thread should call this API before passing `func` to any other thread-safe function APIs to indicate that it will be making use of `func`. This prevents `func` from being destroyed when all other threads have stopped making use of it. This API may be called from any thread which will start making use of `func`. ### `napi\_release\_threadsafe\_function` ```c NAPI\_EXTERN napi\_status napi\_release\_threadsafe\_function(napi\_threadsafe\_function func, napi\_threadsafe\_function\_release\_mode mode); ``` \* `[in] func`: The asynchronous thread-safe JavaScript function whose reference count to decrement. \* `[in] mode`: Flag whose value can be either `napi\_tsfn\_release` to indicate that the current thread will make no further calls to the thread-safe function, or `napi\_tsfn\_abort` to indicate that in addition to the current thread, no other thread should make any further calls to the thread-safe function. If set to `napi\_tsfn\_abort`, further calls to `napi\_call\_threadsafe\_function()` will return `napi\_closing`, and no further values | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.11396938562393188,
0.026596583425998688,
-0.08752653002738953,
0.04703536257147789,
-0.01534861046820879,
-0.09190904349088669,
0.11832159012556076,
0.01605854742228985,
0.003965109121054411,
-0.0704970732331276,
-0.018035097047686577,
-0.029815498739480972,
-0.0006271658930927515,
-0.0... | 0.201167 |
the current thread will make no further calls to the thread-safe function, or `napi\_tsfn\_abort` to indicate that in addition to the current thread, no other thread should make any further calls to the thread-safe function. If set to `napi\_tsfn\_abort`, further calls to `napi\_call\_threadsafe\_function()` will return `napi\_closing`, and no further values will be placed in the queue. A thread should call this API when it stops making use of `func`. Passing `func` to any thread-safe APIs after having called this API has undefined results, as `func` may have been destroyed. This API may be called from any thread which will stop making use of `func`. ### `napi\_ref\_threadsafe\_function` ```c NAPI\_EXTERN napi\_status napi\_ref\_threadsafe\_function(node\_api\_basic\_env env, napi\_threadsafe\_function func); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] func`: The thread-safe function to reference. This API is used to indicate that the event loop running on the main thread should not exit until `func` has been destroyed. Similar to [`uv\_ref`][] it is also idempotent. Neither does `napi\_unref\_threadsafe\_function` mark the thread-safe functions as able to be destroyed nor does `napi\_ref\_threadsafe\_function` prevent it from being destroyed. `napi\_acquire\_threadsafe\_function` and `napi\_release\_threadsafe\_function` are available for that purpose. This API may only be called from the main thread. ### `napi\_unref\_threadsafe\_function` ```c NAPI\_EXTERN napi\_status napi\_unref\_threadsafe\_function(node\_api\_basic\_env env, napi\_threadsafe\_function func); ``` \* `[in] env`: The environment that the API is invoked under. \* `[in] func`: The thread-safe function to unreference. This API is used to indicate that the event loop running on the main thread may exit before `func` is destroyed. Similar to [`uv\_unref`][] it is also idempotent. This API may only be called from the main thread. ## Miscellaneous utilities ### `node\_api\_get\_module\_file\_name` ```c NAPI\_EXTERN napi\_status node\_api\_get\_module\_file\_name(node\_api\_basic\_env env, const char\*\* result); ``` \* `[in] env`: The environment that the API is invoked under. \* `[out] result`: A URL containing the absolute path of the location from which the add-on was loaded. For a file on the local file system it will start with `file://`. The string is null-terminated and owned by `env` and must thus not be modified or freed. `result` may be an empty string if the add-on loading process fails to establish the add-on's file name during loading. [ABI Stability]: https://nodejs.org/en/docs/guides/abi-stability/ [AppVeyor]: https://www.appveyor.com [C++ Addons]: addons.md [CMake]: https://cmake.org [CMake.js]: https://github.com/cmake-js/cmake-js [ECMAScript Language Specification]: https://tc39.es/ecma262/ [Error handling]: #error-handling [GCC]: https://gcc.gnu.org [GYP]: https://gyp.gsrc.io [GitHub releases]: https://help.github.com/en/github/administering-a-repository/about-releases [LLVM]: https://llvm.org [Native Abstractions for Node.js]: https://github.com/nodejs/nan [Node-API Media]: https://github.com/nodejs/abi-stable-node/blob/HEAD/node-api-media.md [Object lifetime management]: #object-lifetime-management [Object wrap]: #object-wrap [Section Agents]: https://tc39.es/ecma262/#sec-agents [Section Array instance length]: https://tc39.es/ecma262/#sec-properties-of-array-instances-length [Section Array objects]: https://tc39.es/ecma262/#sec-array-objects [Section ArrayBuffer objects]: https://tc39.es/ecma262/#sec-arraybuffer-objects [Section DataView objects]: https://tc39.es/ecma262/#sec-dataview-objects [Section Date objects]: https://tc39.es/ecma262/#sec-date-objects [Section DefineOwnProperty]: https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc [Section Function objects]: https://tc39.es/ecma262/#sec-function-objects [Section IsArray]: https://tc39.es/ecma262/#sec-isarray [Section IsStrctEqual]: https://tc39.es/ecma262/#sec-strict-equality-comparison [Section Promise objects]: https://tc39.es/ecma262/#sec-promise-objects [Section SharedArrayBuffer objects]: https://tc39.es/ecma262/#sec-sharedarraybuffer-objects [Section ToBoolean]: https://tc39.es/ecma262/#sec-toboolean [Section ToNumber]: https://tc39.es/ecma262/#sec-tonumber [Section ToObject]: https://tc39.es/ecma262/#sec-toobject [Section ToString]: https://tc39.es/ecma262/#sec-tostring [Section TypedArray objects]: https://tc39.es/ecma262/#sec-typedarray-objects [Section detachArrayBuffer]: https://tc39.es/ecma262/#sec-detacharraybuffer [Section instanceof operator]: https://tc39.es/ecma262/#sec-instanceofoperator [Section isDetachedBuffer]: https://tc39.es/ecma262/#sec-isdetachedbuffer [Section language types]: https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values [Section number type]: https://tc39.es/ecma262/#sec-ecmascript-language-types-number-type [Section object type]: https://tc39.es/ecma262/#sec-object-type [Section property attributes]: https://tc39.es/ecma262/#sec-property-attributes [Section string type]: https://tc39.es/ecma262/#sec-ecmascript-language-types-string-type [Section symbol type]: https://tc39.es/ecma262/#sec-ecmascript-language-types-symbol-type [Section typeof operator]: https://tc39.es/ecma262/#sec-typeof-operator [Travis CI]: https://travis-ci.org [Visual Studio]: https://visualstudio.microsoft.com [Working with JavaScript properties]: #working-with-javascript-properties [Xcode]: https://developer.apple.com/xcode/ [`'uncaughtException'`]: process.md#event-uncaughtexception [`Number.MAX\_SAFE\_INTEGER`]: https://tc39.es/ecma262/#sec-number.max\_safe\_integer [`Number.MIN\_SAFE\_INTEGER`]: https://tc39.es/ecma262/#sec-number.min\_safe\_integer [`Worker`]: worker\_threads.md#class-worker [`async\_hooks.executionAsyncResource()`]: async\_hooks.md#async\_hooksexecutionasyncresource [`build\_with\_cmake`]: https://github.com/nodejs/node-addon-examples/tree/main/src/8-tooling/build\_with\_cmake [`global`]: globals.md#global [`init` hooks]: async\_hooks.md#initasyncid-type-triggerasyncid-resource [`napi\_add\_async\_cleanup\_hook`]: #napi\_add\_async\_cleanup\_hook [`napi\_add\_env\_cleanup\_hook`]: #napi\_add\_env\_cleanup\_hook [`napi\_add\_finalizer`]: #napi\_add\_finalizer [`napi\_async\_cleanup\_hook`]: #napi\_async\_cleanup\_hook [`napi\_async\_complete\_callback`]: #napi\_async\_complete\_callback [`napi\_async\_destroy`]: #napi\_async\_destroy [`napi\_async\_init`]: #napi\_async\_init [`napi\_callback`]: #napi\_callback [`napi\_cancel\_async\_work`]: #napi\_cancel\_async\_work [`napi\_close\_callback\_scope`]: #napi\_close\_callback\_scope [`napi\_close\_escapable\_handle\_scope`]: #napi\_close\_escapable\_handle\_scope [`napi\_close\_handle\_scope`]: #napi\_close\_handle\_scope [`napi\_create\_async\_work`]: #napi\_create\_async\_work [`napi\_create\_error`]: #napi\_create\_error [`napi\_create\_external\_arraybuffer`]: #napi\_create\_external\_arraybuffer [`napi\_create\_range\_error`]: #napi\_create\_range\_error [`napi\_create\_reference`]: #napi\_create\_reference [`napi\_create\_type\_error`]: #napi\_create\_type\_error [`napi\_define\_class`]: #napi\_define\_class [`napi\_delete\_async\_work`]: #napi\_delete\_async\_work [`napi\_delete\_reference`]: #napi\_delete\_reference [`napi\_escape\_handle`]: #napi\_escape\_handle [`napi\_finalize`]: #napi\_finalize [`napi\_get\_and\_clear\_last\_exception`]: #napi\_get\_and\_clear\_last\_exception [`napi\_get\_array\_length`]: #napi\_get\_array\_length [`napi\_get\_element`]: #napi\_get\_element [`napi\_get\_last\_error\_info`]: #napi\_get\_last\_error\_info [`napi\_get\_property`]: #napi\_get\_property [`napi\_get\_reference\_value`]: #napi\_get\_reference\_value [`napi\_get\_typedarray\_info`]: #napi\_get\_typedarray\_info [`napi\_get\_value\_external`]: #napi\_get\_value\_external [`napi\_has\_property`]: #napi\_has\_property [`napi\_instanceof`]: #napi\_instanceof [`napi\_is\_error`]: #napi\_is\_error | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.08796589821577072,
0.003006434766575694,
-0.06975054740905762,
-0.0246894434094429,
0.001007726532407105,
-0.04223468527197838,
0.05735572800040245,
-0.0665651187300682,
0.02598220482468605,
-0.006669447757303715,
0.018012966960668564,
-0.04400583356618881,
-0.051439329981803894,
-0.019... | 0.189674 |
[`napi\_close\_callback\_scope`]: #napi\_close\_callback\_scope [`napi\_close\_escapable\_handle\_scope`]: #napi\_close\_escapable\_handle\_scope [`napi\_close\_handle\_scope`]: #napi\_close\_handle\_scope [`napi\_create\_async\_work`]: #napi\_create\_async\_work [`napi\_create\_error`]: #napi\_create\_error [`napi\_create\_external\_arraybuffer`]: #napi\_create\_external\_arraybuffer [`napi\_create\_range\_error`]: #napi\_create\_range\_error [`napi\_create\_reference`]: #napi\_create\_reference [`napi\_create\_type\_error`]: #napi\_create\_type\_error [`napi\_define\_class`]: #napi\_define\_class [`napi\_delete\_async\_work`]: #napi\_delete\_async\_work [`napi\_delete\_reference`]: #napi\_delete\_reference [`napi\_escape\_handle`]: #napi\_escape\_handle [`napi\_finalize`]: #napi\_finalize [`napi\_get\_and\_clear\_last\_exception`]: #napi\_get\_and\_clear\_last\_exception [`napi\_get\_array\_length`]: #napi\_get\_array\_length [`napi\_get\_element`]: #napi\_get\_element [`napi\_get\_last\_error\_info`]: #napi\_get\_last\_error\_info [`napi\_get\_property`]: #napi\_get\_property [`napi\_get\_reference\_value`]: #napi\_get\_reference\_value [`napi\_get\_typedarray\_info`]: #napi\_get\_typedarray\_info [`napi\_get\_value\_external`]: #napi\_get\_value\_external [`napi\_has\_property`]: #napi\_has\_property [`napi\_instanceof`]: #napi\_instanceof [`napi\_is\_error`]: #napi\_is\_error [`napi\_is\_exception\_pending`]: #napi\_is\_exception\_pending [`napi\_is\_typedarray`]: #napi\_is\_typedarray [`napi\_make\_callback`]: #napi\_make\_callback [`napi\_open\_callback\_scope`]: #napi\_open\_callback\_scope [`napi\_open\_escapable\_handle\_scope`]: #napi\_open\_escapable\_handle\_scope [`napi\_open\_handle\_scope`]: #napi\_open\_handle\_scope [`napi\_property\_attributes`]: #napi\_property\_attributes [`napi\_property\_descriptor`]: #napi\_property\_descriptor [`napi\_queue\_async\_work`]: #napi\_queue\_async\_work [`napi\_reference\_ref`]: #napi\_reference\_ref [`napi\_reference\_unref`]: #napi\_reference\_unref [`napi\_remove\_async\_cleanup\_hook`]: #napi\_remove\_async\_cleanup\_hook [`napi\_remove\_env\_cleanup\_hook`]: #napi\_remove\_env\_cleanup\_hook [`napi\_set\_instance\_data`]: #napi\_set\_instance\_data [`napi\_set\_property`]: #napi\_set\_property [`napi\_threadsafe\_function\_call\_js`]: #napi\_threadsafe\_function\_call\_js [`napi\_throw\_error`]: #napi\_throw\_error [`napi\_throw\_range\_error`]: #napi\_throw\_range\_error [`napi\_throw\_type\_error`]: #napi\_throw\_type\_error [`napi\_throw`]: #napi\_throw [`napi\_unwrap`]: #napi\_unwrap [`napi\_wrap`]: #napi\_wrap [`node-addon-api`]: https://github.com/nodejs/node-addon-api [`node\_api.h`]: https://github.com/nodejs/node/blob/HEAD/src/node\_api.h [`node\_api\_basic\_finalize`]: #node\_api\_basic\_finalize [`node\_api\_create\_external\_string\_latin1`]: #node\_api\_create\_external\_string\_latin1 [`node\_api\_create\_external\_string\_utf16`]: #node\_api\_create\_external\_string\_utf16 [`node\_api\_create\_syntax\_error`]: #node\_api\_create\_syntax\_error [`node\_api\_post\_finalizer`]: #node\_api\_post\_finalizer [`node\_api\_throw\_syntax\_error`]: #node\_api\_throw\_syntax\_error [`process.release`]: process.md#processrelease [`uv\_ref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv\_ref [`uv\_unref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv\_unref [`worker.terminate()`]: worker\_threads.md#workerterminate [async\_hooks `type`]: async\_hooks.md#type [context-aware addons]: addons.md#context-aware-addons [docs]: https://github.com/nodejs/node-addon-api#api-documentation [external]: #napi\_create\_external [externals]: #napi\_create\_external [global scope]: globals.md [gyp-next]: https://github.com/nodejs/gyp-next [language and engine bindings]: https://github.com/nodejs/abi-stable-node/blob/doc/node-api-engine-bindings.md [module scope]: modules.md#the-module-scope [node-gyp]: https://github.com/nodejs/node-gyp [node-pre-gyp]: https://github.com/mapbox/node-pre-gyp [prebuild]: https://github.com/prebuild/prebuild [prebuildify]: https://github.com/prebuild/prebuildify [worker threads]: https://nodejs.org/api/worker\_threads.html | https://github.com/nodejs/node/blob/main//doc/api/n-api.md | main | nodejs | [
-0.0470927469432354,
0.03785688057541847,
-0.11318910121917725,
0.021302999928593636,
-0.06382657587528229,
-0.06934966892004013,
0.06299711018800735,
-0.013099719770252705,
-0.004737635143101215,
-0.042790062725543976,
-0.008200759999454021,
-0.079280786216259,
-0.03635607659816742,
-0.00... | 0.161662 |
# Diagnostic report > Stability: 2 - Stable Delivers a JSON-formatted diagnostic summary, written to a file. The report is intended for development, test, and production use, to capture and preserve information for problem determination. It includes JavaScript and native stack traces, heap statistics, platform information, resource usage etc. With the report option enabled, diagnostic reports can be triggered on unhandled exceptions, fatal errors and user signals, in addition to triggering programmatically through API calls. A complete example report that was generated on an uncaught exception is provided below for reference. ```json { "header": { "reportVersion": 5, "event": "exception", "trigger": "Exception", "filename": "report.20181221.005011.8974.0.001.json", "dumpEventTime": "2018-12-21T00:50:11Z", "dumpEventTimeStamp": "1545371411331", "processId": 8974, "cwd": "/home/nodeuser/project/node", "commandLine": [ "/home/nodeuser/project/node/out/Release/node", "--report-uncaught-exception", "/home/nodeuser/project/node/test/report/test-exception.js", "child" ], "nodejsVersion": "v12.0.0-pre", "glibcVersionRuntime": "2.17", "glibcVersionCompiler": "2.17", "wordSize": "64 bit", "arch": "x64", "platform": "linux", "componentVersions": { "node": "12.0.0-pre", "v8": "7.1.302.28-node.5", "uv": "1.24.1", "zlib": "1.2.11", "ares": "1.15.0", "modules": "68", "nghttp2": "1.34.0", "napi": "3", "llhttp": "1.0.1", "openssl": "1.1.0j" }, "release": { "name": "node" }, "osName": "Linux", "osRelease": "3.10.0-862.el7.x86\_64", "osVersion": "#1 SMP Wed Mar 21 18:14:51 EDT 2018", "osMachine": "x86\_64", "cpus": [ { "model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz", "speed": 2700, "user": 88902660, "nice": 0, "sys": 50902570, "idle": 241732220, "irq": 0 }, { "model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz", "speed": 2700, "user": 88902660, "nice": 0, "sys": 50902570, "idle": 241732220, "irq": 0 } ], "networkInterfaces": [ { "name": "en0", "internal": false, "mac": "13:10:de:ad:be:ef", "address": "10.0.0.37", "netmask": "255.255.255.0", "family": "IPv4" } ], "host": "test\_machine" }, "javascriptStack": { "message": "Error: \*\*\* test-exception.js: throwing uncaught Error", "stack": [ "at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)", "at Object. (/home/nodeuser/project/node/test/report/test-exception.js:12:3)", "at Module.\_compile (internal/modules/cjs/loader.js:718:30)", "at Object.Module.\_extensions..js (internal/modules/cjs/loader.js:729:10)", "at Module.load (internal/modules/cjs/loader.js:617:32)", "at tryModuleLoad (internal/modules/cjs/loader.js:560:12)", "at Function.Module.\_load (internal/modules/cjs/loader.js:552:3)", "at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)", "at executeUserCode (internal/bootstrap/node.js:332:15)" ] }, "nativeStack": [ { "pc": "0x000055b57f07a9ef", "symbol": "report::GetNodeReport(v8::Isolate\*, node::Environment\*, char const\*, char const\*, v8::Local, std::ostream&) [./node]" }, { "pc": "0x000055b57f07cf03", "symbol": "report::GetReport(v8::FunctionCallbackInfo const&) [./node]" }, { "pc": "0x000055b57f1bccfd", "symbol": " [./node]" }, { "pc": "0x000055b57f1be048", "symbol": "v8::internal::Builtin\_HandleApiCall(int, v8::internal::Object\*\*, v8::internal::Isolate\*) [./node]" }, { "pc": "0x000055b57feeda0e", "symbol": " [./node]" } ], "javascriptHeap": { "totalMemory": 5660672, "executableMemory": 524288, "totalCommittedMemory": 5488640, "availableMemory": 4341379928, "totalGlobalHandlesMemory": 8192, "usedGlobalHandlesMemory": 3136, "usedMemory": 4816432, "memoryLimit": 4345298944, "mallocedMemory": 254128, "externalMemory": 315644, "peakMallocedMemory": 98752, "nativeContextCount": 1, "detachedContextCount": 0, "doesZapGarbage": 0, "heapSpaces": { "read\_only\_space": { "memorySize": 524288, "committedMemory": 39208, "capacity": 515584, "used": 30504, "available": 485080 }, "new\_space": { "memorySize": 2097152, "committedMemory": 2019312, "capacity": 1031168, "used": 985496, "available": 45672 }, "old\_space": { "memorySize": 2273280, "committedMemory": 1769008, "capacity": 1974640, "used": 1725488, "available": 249152 }, "code\_space": { "memorySize": 696320, "committedMemory": 184896, "capacity": 152128, "used": 152128, "available": 0 }, "map\_space": { "memorySize": 536576, "committedMemory": 344928, "capacity": 327520, "used": 327520, "available": 0 }, "large\_object\_space": { "memorySize": 0, "committedMemory": 0, "capacity": 1520590336, "used": 0, "available": 1520590336 }, "new\_large\_object\_space": { "memorySize": 0, "committedMemory": 0, "capacity": 0, "used": 0, "available": 0 } } }, "resourceUsage": { "rss": "35766272", "free\_memory": "1598337024", "total\_memory": "17179869184", "available\_memory": "1598337024", "maxRss": "36624662528", "constrained\_memory": "36624662528", "userCpuSeconds": 0.040072, "kernelCpuSeconds": 0.016029, "cpuConsumptionPercent": 5.6101, "userCpuConsumptionPercent": 4.0072, "kernelCpuConsumptionPercent": 1.6029, "pageFaults": { "IORequired": 0, "IONotRequired": 4610 }, "fsActivity": { "reads": 0, "writes": 0 } }, "uvthreadResourceUsage": { "userCpuSeconds": 0.039843, "kernelCpuSeconds": 0.015937, "cpuConsumptionPercent": 5.578, "userCpuConsumptionPercent": 3.9843, "kernelCpuConsumptionPercent": 1.5937, "fsActivity": { "reads": 0, "writes": 0 } }, "libuv": [ { "type": "async", "is\_active": true, "is\_referenced": false, "address": "0x0000000102910900", "details": "" }, { "type": "timer", "is\_active": false, "is\_referenced": false, "address": "0x00007fff5fbfeab0", "repeat": 0, "firesInMsFromNow": 94403548320796, "expired": true }, { "type": "check", "is\_active": true, "is\_referenced": false, "address": "0x00007fff5fbfeb48" }, { "type": "idle", "is\_active": false, "is\_referenced": true, "address": "0x00007fff5fbfebc0" }, { "type": "prepare", "is\_active": false, "is\_referenced": false, "address": "0x00007fff5fbfec38" }, { "type": "check", "is\_active": false, "is\_referenced": false, "address": "0x00007fff5fbfecb0" }, { "type": "async", "is\_active": true, "is\_referenced": false, "address": "0x000000010188f2e0" }, { "type": "tty", "is\_active": false, "is\_referenced": true, "address": "0x000055b581db0e18", | https://github.com/nodejs/node/blob/main//doc/api/report.md | main | nodejs | [
-0.03155870735645294,
0.04952438548207283,
-0.07357687503099442,
0.08114887028932571,
0.05973784625530243,
-0.019237907603383064,
-0.05317432060837746,
0.11818104237318039,
-0.017385419458150864,
-0.0009436236578039825,
-0.010711691342294216,
-0.00016617953951936215,
0.03630038723349571,
0... | 0.163263 |
}, { "type": "idle", "is\_active": false, "is\_referenced": true, "address": "0x00007fff5fbfebc0" }, { "type": "prepare", "is\_active": false, "is\_referenced": false, "address": "0x00007fff5fbfec38" }, { "type": "check", "is\_active": false, "is\_referenced": false, "address": "0x00007fff5fbfecb0" }, { "type": "async", "is\_active": true, "is\_referenced": false, "address": "0x000000010188f2e0" }, { "type": "tty", "is\_active": false, "is\_referenced": true, "address": "0x000055b581db0e18", "width": 204, "height": 55, "fd": 17, "writeQueueSize": 0, "readable": true, "writable": true }, { "type": "signal", "is\_active": true, "is\_referenced": false, "address": "0x000055b581d80010", "signum": 28, "signal": "SIGWINCH" }, { "type": "tty", "is\_active": true, "is\_referenced": true, "address": "0x000055b581df59f8", "width": 204, "height": 55, "fd": 19, "writeQueueSize": 0, "readable": true, "writable": true }, { "type": "loop", "is\_active": true, "address": "0x000055fc7b2cb180", "loopIdleTimeSeconds": 22644.8 }, { "type": "tcp", "is\_active": true, "is\_referenced": true, "address": "0x000055e70fcb85d8", "localEndpoint": { "host": "localhost", "ip4": "127.0.0.1", "port": 48986 }, "remoteEndpoint": { "host": "localhost", "ip4": "127.0.0.1", "port": 38573 }, "sendBufferSize": 2626560, "recvBufferSize": 131072, "fd": 24, "writeQueueSize": 0, "readable": true, "writable": true } ], "workers": [], "environmentVariables": { "REMOTEHOST": "REMOVED", "MANPATH": "/opt/rh/devtoolset-3/root/usr/share/man:", "XDG\_SESSION\_ID": "66126", "HOSTNAME": "test\_machine", "HOST": "test\_machine", "TERM": "xterm-256color", "SHELL": "/bin/csh", "SSH\_CLIENT": "REMOVED", "PERL5LIB": "/opt/rh/devtoolset-3/root//usr/lib64/perl5/vendor\_perl:/opt/rh/devtoolset-3/root/usr/lib/perl5:/opt/rh/devtoolset-3/root//usr/share/perl5/vendor\_perl", "OLDPWD": "/home/nodeuser/project/node/src", "JAVACONFDIRS": "/opt/rh/devtoolset-3/root/etc/java:/etc/java", "SSH\_TTY": "/dev/pts/0", "PCP\_DIR": "/opt/rh/devtoolset-3/root", "GROUP": "normaluser", "USER": "nodeuser", "LD\_LIBRARY\_PATH": "/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib", "HOSTTYPE": "x86\_64-linux", "XDG\_CONFIG\_DIRS": "/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg", "MAIL": "/var/spool/mail/nodeuser", "PATH": "/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin", "PWD": "/home/nodeuser/project/node", "LANG": "en\_US.UTF-8", "PS1": "\\u@\\h : \\[\\e[31m\\]\\w\\[\\e[m\\] > ", "SHLVL": "2", "HOME": "/home/nodeuser", "OSTYPE": "linux", "VENDOR": "unknown", "PYTHONPATH": "/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages", "MACHTYPE": "x86\_64", "LOGNAME": "nodeuser", "XDG\_DATA\_DIRS": "/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share", "LESSOPEN": "||/usr/bin/lesspipe.sh %s", "INFOPATH": "/opt/rh/devtoolset-3/root/usr/share/info", "XDG\_RUNTIME\_DIR": "/run/user/50141", "\_": "./node" }, "userLimits": { "core\_file\_size\_blocks": { "soft": "", "hard": "unlimited" }, "data\_seg\_size\_bytes": { "soft": "unlimited", "hard": "unlimited" }, "file\_size\_blocks": { "soft": "unlimited", "hard": "unlimited" }, "max\_locked\_memory\_bytes": { "soft": "unlimited", "hard": 65536 }, "max\_memory\_size\_bytes": { "soft": "unlimited", "hard": "unlimited" }, "open\_files": { "soft": "unlimited", "hard": 4096 }, "stack\_size\_bytes": { "soft": "unlimited", "hard": "unlimited" }, "cpu\_time\_seconds": { "soft": "unlimited", "hard": "unlimited" }, "max\_user\_processes": { "soft": "unlimited", "hard": 4127290 }, "virtual\_memory\_bytes": { "soft": "unlimited", "hard": "unlimited" } }, "sharedObjects": [ "/lib64/libdl.so.2", "/lib64/librt.so.1", "/lib64/libstdc++.so.6", "/lib64/libm.so.6", "/lib64/libgcc\_s.so.1", "/lib64/libpthread.so.0", "/lib64/libc.so.6", "/lib64/ld-linux-x86-64.so.2" ] } ``` ## Usage ```bash node --report-uncaught-exception --report-on-signal \ --report-on-fatalerror app.js ``` \* `--report-uncaught-exception` Enables report to be generated on un-caught exceptions. Useful when inspecting JavaScript stack in conjunction with native stack and other runtime environment data. \* `--report-on-signal` Enables report to be generated upon receiving the specified (or predefined) signal to the running Node.js process. (See below on how to modify the signal that triggers the report.) Default signal is `SIGUSR2`. Useful when a report needs to be triggered from another program. Application monitors may leverage this feature to collect report at regular intervals and plot rich set of internal runtime data to their views. Signal based report generation is not supported in Windows. Under normal circumstances, there is no need to modify the report triggering signal. However, if `SIGUSR2` is already used for other purposes, then this flag helps to change the signal for report generation and preserve the original meaning of `SIGUSR2` for the said purposes. \* `--report-on-fatalerror` Enables the report to be triggered on fatal errors (internal errors within the Node.js runtime, such as out of memory) that leads to termination of the application. Useful to inspect various diagnostic data elements such as heap, stack, event loop state, resource consumption etc. to reason about the fatal error. \* `--report-compact` Write reports in a compact format, single-line JSON, more easily consumable by log processing systems than the default multi-line format designed for human consumption. \* `--report-directory` Location at which the report will be generated. \* `--report-filename` Name of the file to which the report will be written. \* `--report-signal` Sets or resets the signal for report generation (not supported on Windows). Default signal is `SIGUSR2`. \* `--report-exclude-network` Exclude `header.networkInterfaces` and disable the reverse | https://github.com/nodejs/node/blob/main//doc/api/report.md | main | nodejs | [
-0.027484282851219177,
0.021915489807724953,
-0.08434611558914185,
0.11684130877256393,
0.001123656751587987,
-0.05107993632555008,
0.06301713734865189,
-0.03608906269073486,
0.019853761419653893,
-0.011712317354977131,
-0.028296707198023796,
-0.049911774694919586,
-0.0058882287703454494,
... | 0.117825 |
consumption. \* `--report-directory` Location at which the report will be generated. \* `--report-filename` Name of the file to which the report will be written. \* `--report-signal` Sets or resets the signal for report generation (not supported on Windows). Default signal is `SIGUSR2`. \* `--report-exclude-network` Exclude `header.networkInterfaces` and disable the reverse DNS queries in `libuv.\*.(remote|local)Endpoint.host` from the diagnostic report. By default this is not set and the network interfaces are included. \* `--report-exclude-env` Exclude `environmentVariables` from the diagnostic report. By default this is not set and the environment variables are included. A report can also be triggered via an API call from a JavaScript application: ```js process.report.writeReport(); ``` This function takes an optional additional argument `filename`, which is the name of a file into which the report is written. ```js process.report.writeReport('./foo.json'); ``` This function takes an optional additional argument `err` which is an `Error` object that will be used as the context for the JavaScript stack printed in the report. When using report to handle errors in a callback or an exception handler, this allows the report to include the location of the original error as well as where it was handled. ```js try { process.chdir('/non-existent-path'); } catch (err) { process.report.writeReport(err); } // Any other code ``` If both filename and error object are passed to `writeReport()` the error object must be the second parameter. ```js try { process.chdir('/non-existent-path'); } catch (err) { process.report.writeReport(filename, err); } // Any other code ``` The content of the diagnostic report can be returned as a JavaScript Object via an API call from a JavaScript application: ```js const report = process.report.getReport(); console.log(typeof report === 'object'); // true // Similar to process.report.writeReport() output console.log(JSON.stringify(report, null, 2)); ``` This function takes an optional additional argument `err`, which is an `Error` object that will be used as the context for the JavaScript stack printed in the report. ```js const report = process.report.getReport(new Error('custom error')); console.log(typeof report === 'object'); // true ``` The API versions are useful when inspecting the runtime state from within the application, in expectation of self-adjusting the resource consumption, load balancing, monitoring etc. The content of the report consists of a header section containing the event type, date, time, PID, and Node.js version, sections containing JavaScript and native stack traces, a section containing V8 heap information, a section containing `libuv` handle information, and an OS platform information section showing CPU and memory usage and system limits. An example report can be triggered using the Node.js REPL: ```console $ node > process.report.writeReport(); Writing Node.js report to file: report.20181126.091102.8480.0.001.json Node.js report completed > ``` When a report is written, start and end messages are issued to stderr and the filename of the report is returned to the caller. The default filename includes the date, time, PID, and a sequence number. The sequence number helps in associating the report dump with the runtime state if generated multiple times for the same Node.js process. ## Report Version Diagnostic report has an associated single-digit version number (`report.header.reportVersion`), uniquely representing the report format. The version number is bumped when new key is added or removed, or the data type of a value is changed. Report version definitions are consistent across LTS releases. ### Version history #### Version 5 Replace the keys `data\_seg\_size\_kbytes`, `max\_memory\_size\_kbytes`, and `virtual\_memory\_kbytes` with `data\_seg\_size\_bytes`, `max\_memory\_size\_bytes`, and `virtual\_memory\_bytes` respectively in the `userLimits` section, as these values are given in bytes. ```json { "userLimits": { // Skip some keys ... "data\_seg\_size\_bytes": { // replacing data\_seg\_size\_kbytes "soft": "unlimited", "hard": "unlimited" }, // ... "max\_memory\_size\_bytes": { // replacing max\_memory\_size\_kbytes "soft": "unlimited", "hard": "unlimited" }, // ... "virtual\_memory\_bytes": { // replacing virtual\_memory\_kbytes "soft": | https://github.com/nodejs/node/blob/main//doc/api/report.md | main | nodejs | [
-0.007025266066193581,
0.0322473868727684,
-0.07412528991699219,
0.08036143332719803,
0.03963159769773483,
-0.0011150374775752425,
-0.028946008533239365,
0.06007172539830208,
0.011727464385330677,
-0.023135956376791,
-0.00317776040174067,
0.006882910616695881,
0.03894837573170662,
-0.01155... | 0.044152 |
in the `userLimits` section, as these values are given in bytes. ```json { "userLimits": { // Skip some keys ... "data\_seg\_size\_bytes": { // replacing data\_seg\_size\_kbytes "soft": "unlimited", "hard": "unlimited" }, // ... "max\_memory\_size\_bytes": { // replacing max\_memory\_size\_kbytes "soft": "unlimited", "hard": "unlimited" }, // ... "virtual\_memory\_bytes": { // replacing virtual\_memory\_kbytes "soft": "unlimited", "hard": "unlimited" } } } ``` #### Version 4 New fields `ipv4` and `ipv6` are added to `tcp` and `udp` libuv handles endpoints. Examples: ```json { "libuv": [ { "type": "tcp", "is\_active": true, "is\_referenced": true, "address": "0x000055e70fcb85d8", "localEndpoint": { "host": "localhost", "ip4": "127.0.0.1", // new key "port": 48986 }, "remoteEndpoint": { "host": "localhost", "ip4": "127.0.0.1", // new key "port": 38573 }, "sendBufferSize": 2626560, "recvBufferSize": 131072, "fd": 24, "writeQueueSize": 0, "readable": true, "writable": true }, { "type": "tcp", "is\_active": true, "is\_referenced": true, "address": "0x000055e70fcd68c8", "localEndpoint": { "host": "ip6-localhost", "ip6": "::1", // new key "port": 52266 }, "remoteEndpoint": { "host": "ip6-localhost", "ip6": "::1", // new key "port": 38573 }, "sendBufferSize": 2626560, "recvBufferSize": 131072, "fd": 25, "writeQueueSize": 0, "readable": false, "writable": false } ] } ``` #### Version 3 The following memory usage keys are added to the `resourceUsage` section. ```json { "resourceUsage": { "rss": "35766272", "free\_memory": "1598337024", "total\_memory": "17179869184", "available\_memory": "1598337024", "constrained\_memory": "36624662528" } } ``` #### Version 2 Added [`Worker`][] support. Refer to [Interaction with workers](#interaction-with-workers) section for more details. #### Version 1 This is the first version of the diagnostic report. ## Configuration Additional runtime configuration of report generation is available via the following properties of `process.report`: `reportOnFatalError` triggers diagnostic reporting on fatal errors when `true`. Defaults to `false`. `reportOnSignal` triggers diagnostic reporting on signal when `true`. This is not supported on Windows. Defaults to `false`. `reportOnUncaughtException` triggers diagnostic reporting on uncaught exception when `true`. Defaults to `false`. `signal` specifies the POSIX signal identifier that will be used to intercept external triggers for report generation. Defaults to `'SIGUSR2'`. `filename` specifies the name of the output file in the file system. Special meaning is attached to `stdout` and `stderr`. Usage of these will result in report being written to the associated standard streams. In cases where standard streams are used, the value in `directory` is ignored. URLs are not supported. Defaults to a composite filename that contains timestamp, PID, and sequence number. `directory` specifies the file system directory where the report will be written. URLs are not supported. Defaults to the current working directory of the Node.js process. `excludeNetwork` excludes `header.networkInterfaces` from the diagnostic report. ```js // Trigger report only on uncaught exceptions. process.report.reportOnFatalError = false; process.report.reportOnSignal = false; process.report.reportOnUncaughtException = true; // Trigger report for both internal errors as well as external signal. process.report.reportOnFatalError = true; process.report.reportOnSignal = true; process.report.reportOnUncaughtException = false; // Change the default signal to 'SIGQUIT' and enable it. process.report.reportOnFatalError = false; process.report.reportOnUncaughtException = false; process.report.reportOnSignal = true; process.report.signal = 'SIGQUIT'; // Disable network interfaces reporting process.report.excludeNetwork = true; ``` Configuration on module initialization is also available via environment variables: ```bash NODE\_OPTIONS="--report-uncaught-exception \ --report-on-fatalerror --report-on-signal \ --report-signal=SIGUSR2 --report-filename=./report.json \ --report-directory=/home/nodeuser" ``` Specific API documentation can be found under [`process API documentation`][] section. ## Interaction with workers [`Worker`][] threads can create reports in the same way that the main thread does. Reports will include information on any Workers that are children of the current thread as part of the `workers` section, with each Worker generating a report in the standard report format. The thread which is generating the report will wait for the reports from Worker threads to finish. However, the latency for this will usually be low, as both running JavaScript and the event loop are interrupted to generate the report. [`Worker`]: worker\_threads.md [`process API documentation`]: | https://github.com/nodejs/node/blob/main//doc/api/report.md | main | nodejs | [
0.005882115103304386,
0.0375773087143898,
-0.05222398415207863,
-0.02660983055830002,
-0.0018934388644993305,
-0.057658687233924866,
0.023724593222141266,
0.04622269794344902,
-0.01289066206663847,
-0.02386840432882309,
0.03506957367062569,
0.002004403155297041,
0.0027036836836487055,
-0.0... | 0.081623 |
in the standard report format. The thread which is generating the report will wait for the reports from Worker threads to finish. However, the latency for this will usually be low, as both running JavaScript and the event loop are interrupted to generate the report. [`Worker`]: worker\_threads.md [`process API documentation`]: process.md | https://github.com/nodejs/node/blob/main//doc/api/report.md | main | nodejs | [
-0.07156629860401154,
0.016766440123319626,
-0.11042369902133942,
0.054148491472005844,
0.04969143122434616,
-0.029582468792796135,
-0.08015350997447968,
-0.025148574262857437,
0.0990012139081955,
0.0076461974531412125,
-0.02223709225654602,
0.05994052812457085,
-0.012864968739449978,
-0.0... | 0.132057 |
# String decoder > Stability: 2 - Stable The `node:string\_decoder` module provides an API for decoding `Buffer` objects into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 characters. It can be accessed using: ```mjs import { StringDecoder } from 'node:string\_decoder'; ``` ```cjs const { StringDecoder } = require('node:string\_decoder'); ``` The following example shows the basic use of the `StringDecoder` class. ```mjs import { StringDecoder } from 'node:string\_decoder'; import { Buffer } from 'node:buffer'; const decoder = new StringDecoder('utf8'); const cent = Buffer.from([0xC2, 0xA2]); console.log(decoder.write(cent)); // Prints: ¢ const euro = Buffer.from([0xE2, 0x82, 0xAC]); console.log(decoder.write(euro)); // Prints: € ``` ```cjs const { StringDecoder } = require('node:string\_decoder'); const decoder = new StringDecoder('utf8'); const cent = Buffer.from([0xC2, 0xA2]); console.log(decoder.write(cent)); // Prints: ¢ const euro = Buffer.from([0xE2, 0x82, 0xAC]); console.log(decoder.write(euro)); // Prints: € ``` When a `Buffer` instance is written to the `StringDecoder` instance, an internal buffer is used to ensure that the decoded string does not contain any incomplete multibyte characters. These are held in the buffer until the next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. In the following example, the three UTF-8 encoded bytes of the European Euro symbol (`€`) are written over three separate operations: ```mjs import { StringDecoder } from 'node:string\_decoder'; import { Buffer } from 'node:buffer'; const decoder = new StringDecoder('utf8'); decoder.write(Buffer.from([0xE2])); decoder.write(Buffer.from([0x82])); console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € ``` ```cjs const { StringDecoder } = require('node:string\_decoder'); const decoder = new StringDecoder('utf8'); decoder.write(Buffer.from([0xE2])); decoder.write(Buffer.from([0x82])); console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € ``` ## Class: `StringDecoder` ### `new StringDecoder([encoding])` \* `encoding` {string} The character [encoding][] the `StringDecoder` will use. \*\*Default:\*\* `'utf8'`. Creates a new `StringDecoder` instance. ### `stringDecoder.end([buffer])` \* `buffer` {string|Buffer|TypedArray|DataView} The bytes to decode. \* Returns: {string} Returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be replaced with substitution characters appropriate for the character encoding. If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. After `end()` is called, the `stringDecoder` object can be reused for new input. ### `stringDecoder.write(buffer)` \* `buffer` {string|Buffer|TypedArray|DataView} The bytes to decode. \* Returns: {string} Returns a decoded string, ensuring that any incomplete multibyte characters at the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. [encoding]: buffer.md#buffers-and-character-encodings | https://github.com/nodejs/node/blob/main//doc/api/string_decoder.md | main | nodejs | [
-0.005371804349124432,
0.020492132753133774,
-0.0450509749352932,
-0.0041944729164242744,
-0.04104958847165108,
-0.05159217119216919,
-0.0035255944821983576,
0.06570645421743393,
0.027163216844201088,
-0.027237996459007263,
-0.030461231246590614,
-0.03257817029953003,
0.0062808385118842125,
... | 0.078785 |
# Path > Stability: 2 - Stable The `node:path` module provides utilities for working with file and directory paths. It can be accessed using: ```cjs const path = require('node:path'); ``` ```mjs import path from 'node:path'; ``` ## Windows vs. POSIX The default operation of the `node:path` module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the `node:path` module will assume that Windows-style paths are being used. So using `path.basename()` might yield different results on POSIX and Windows: On POSIX: ```js path.basename('C:\\temp\\myfile.html'); // Returns: 'C:\\temp\\myfile.html' ``` On Windows: ```js path.basename('C:\\temp\\myfile.html'); // Returns: 'myfile.html' ``` To achieve consistent results when working with Windows file paths on any operating system, use [`path.win32`][]: On POSIX and Windows: ```js path.win32.basename('C:\\temp\\myfile.html'); // Returns: 'myfile.html' ``` To achieve consistent results when working with POSIX file paths on any operating system, use [`path.posix`][]: On POSIX and Windows: ```js path.posix.basename('/tmp/myfile.html'); // Returns: 'myfile.html' ``` On Windows Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example, `path.resolve('C:\\')` can potentially return a different result than `path.resolve('C:')`. For more information, see [this MSDN page][MSDN-Rel-Path]. ## `path.basename(path[, suffix])` \* `path` {string} \* `suffix` {string} An optional suffix to remove \* Returns: {string} The `path.basename()` method returns the last portion of a `path`, similar to the Unix `basename` command. Trailing [directory separators][`path.sep`] are ignored. ```js path.basename('/foo/bar/baz/asdf/quux.html'); // Returns: 'quux.html' path.basename('/foo/bar/baz/asdf/quux.html', '.html'); // Returns: 'quux' ``` Although Windows usually treats file names, including file extensions, in a case-insensitive manner, this function does not. For example, `C:\\foo.html` and `C:\\foo.HTML` refer to the same file, but `basename` treats the extension as a case-sensitive string: ```js path.win32.basename('C:\\foo.html', '.html'); // Returns: 'foo' path.win32.basename('C:\\foo.HTML', '.html'); // Returns: 'foo.HTML' ``` A [`TypeError`][] is thrown if `path` is not a string or if `suffix` is given and is not a string. ## `path.delimiter` \* Type: {string} Provides the platform-specific path delimiter: \* `;` for Windows \* `:` for POSIX For example, on POSIX: ```js console.log(process.env.PATH); // Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' process.env.PATH.split(path.delimiter); // Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] ``` On Windows: ```js console.log(process.env.PATH); // Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\' process.env.PATH.split(path.delimiter); // Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\'] ``` ## `path.dirname(path)` \* `path` {string} \* Returns: {string} The `path.dirname()` method returns the directory name of a `path`, similar to the Unix `dirname` command. Trailing directory separators are ignored, see [`path.sep`][]. ```js path.dirname('/foo/bar/baz/asdf/quux'); // Returns: '/foo/bar/baz/asdf' ``` A [`TypeError`][] is thrown if `path` is not a string. ## `path.extname(path)` \* `path` {string} \* Returns: {string} The `path.extname()` method returns the extension of the `path`, from the last occurrence of the `.` (period) character to end of string in the last portion of the `path`. If there is no `.` in the last portion of the `path`, or if there are no `.` characters other than the first character of the basename of `path` (see `path.basename()`) , an empty string is returned. ```js path.extname('index.html'); // Returns: '.html' path.extname('index.coffee.md'); // Returns: '.md' path.extname('index.'); // Returns: '.' path.extname('index'); // Returns: '' path.extname('.index'); // Returns: '' path.extname('.index.md'); // Returns: '.md' ``` A [`TypeError`][] is thrown if `path` is not a string. ## `path.format(pathObject)` \* `pathObject` {Object} Any JavaScript object having the following properties: \* `dir` {string} \* `root` {string} \* `base` {string} \* `name` {string} \* `ext` {string} \* Returns: {string} The `path.format()` method returns a path string from an object. This is the opposite of [`path.parse()`][]. When providing properties to the `pathObject` remember that there are combinations where one property has priority over another: \* `pathObject.root` is ignored if `pathObject.dir` is provided \* `pathObject.ext` and | https://github.com/nodejs/node/blob/main//doc/api/path.md | main | nodejs | [
-0.06645947694778442,
0.0027339444495737553,
-0.011095819063484669,
0.06097820773720741,
0.032893430441617966,
-0.03668994829058647,
-0.04029686376452446,
0.08627273887395859,
0.04849674925208092,
-0.026423882693052292,
-0.03516815975308418,
0.07636712491512299,
-0.002616459270939231,
0.01... | 0.060754 |
`ext` {string} \* Returns: {string} The `path.format()` method returns a path string from an object. This is the opposite of [`path.parse()`][]. When providing properties to the `pathObject` remember that there are combinations where one property has priority over another: \* `pathObject.root` is ignored if `pathObject.dir` is provided \* `pathObject.ext` and `pathObject.name` are ignored if `pathObject.base` exists For example, on POSIX: ```js // If `dir`, `root` and `base` are provided, // `${dir}${path.sep}${base}` // will be returned. `root` is ignored. path.format({ root: '/ignored', dir: '/home/user/dir', base: 'file.txt', }); // Returns: '/home/user/dir/file.txt' // `root` will be used if `dir` is not specified. // If only `root` is provided or `dir` is equal to `root` then the // platform separator will not be included. `ext` will be ignored. path.format({ root: '/', base: 'file.txt', ext: 'ignored', }); // Returns: '/file.txt' // `name` + `ext` will be used if `base` is not specified. path.format({ root: '/', name: 'file', ext: '.txt', }); // Returns: '/file.txt' // The dot will be added if it is not specified in `ext`. path.format({ root: '/', name: 'file', ext: 'txt', }); // Returns: '/file.txt' ``` On Windows: ```js path.format({ dir: 'C:\\path\\dir', base: 'file.txt', }); // Returns: 'C:\\path\\dir\\file.txt' ``` ## `path.matchesGlob(path, pattern)` \* `path` {string} The path to glob-match against. \* `pattern` {string} The glob to check the path against. \* Returns: {boolean} Whether or not the `path` matched the `pattern`. The `path.matchesGlob()` method determines if `path` matches the `pattern`. For example: ```js path.matchesGlob('/foo/bar', '/foo/\*'); // true path.matchesGlob('/foo/bar\*', 'foo/bird'); // false ``` A [`TypeError`][] is thrown if `path` or `pattern` are not strings. ## `path.isAbsolute(path)` \* `path` {string} \* Returns: {boolean} The `path.isAbsolute()` method determines if the literal `path` is absolute. Therefore, it’s not safe for mitigating path traversals. If the given `path` is a zero-length string, `false` will be returned. For example, on POSIX: ```js path.isAbsolute('/foo/bar'); // true path.isAbsolute('/baz/..'); // true path.isAbsolute('/baz/../..'); // true path.isAbsolute('qux/'); // false path.isAbsolute('.'); // false ``` On Windows: ```js path.isAbsolute('//server'); // true path.isAbsolute('\\\\server'); // true path.isAbsolute('C:/foo/..'); // true path.isAbsolute('C:\\foo\\..'); // true path.isAbsolute('bar\\baz'); // false path.isAbsolute('bar/baz'); // false path.isAbsolute('.'); // false ``` A [`TypeError`][] is thrown if `path` is not a string. ## `path.join([...paths])` \* `...paths` {string} A sequence of path segments \* Returns: {string} The `path.join()` method joins all given `path` segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. Zero-length `path` segments are ignored. If the joined path string is a zero-length string then `'.'` will be returned, representing the current working directory. ```js path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // Returns: '/foo/bar/baz/asdf' path.join('foo', {}, 'bar'); // Throws 'TypeError: Path must be a string. Received {}' ``` A [`TypeError`][] is thrown if any of the path segments is not a string. ## `path.normalize(path)` \* `path` {string} \* Returns: {string} The `path.normalize()` method normalizes the given `path`, resolving `'..'` and `'.'` segments. When multiple, sequential path segment separation characters are found (e.g. `/` on POSIX and either `\` or `/` on Windows), they are replaced by a single instance of the platform-specific path segment separator (`/` on POSIX and `\` on Windows). Trailing separators are preserved. If the `path` is a zero-length string, `'.'` is returned, representing the current working directory. On POSIX, the types of normalization applied by this function do not strictly adhere to the POSIX specification. For example, this function will replace two leading forward slashes with a single slash as if it was a regular absolute path, whereas a few POSIX systems assign special meaning to paths beginning with exactly two forward slashes. Similarly, other substitutions performed by this function, such as removing `..` segments, may change how the | https://github.com/nodejs/node/blob/main//doc/api/path.md | main | nodejs | [
-0.0377468466758728,
0.09821570664644241,
-0.022017192095518112,
0.08443716168403625,
-0.06842772662639618,
-0.05106247216463089,
0.00459186639636755,
0.13474713265895844,
0.07237525284290314,
-0.026568779721856117,
0.010649912990629673,
0.02813217043876648,
-0.06350470334291458,
0.0375753... | 0.07372 |
will replace two leading forward slashes with a single slash as if it was a regular absolute path, whereas a few POSIX systems assign special meaning to paths beginning with exactly two forward slashes. Similarly, other substitutions performed by this function, such as removing `..` segments, may change how the underlying system resolves the path. For example, on POSIX: ```js path.normalize('/foo/bar//baz/asdf/quux/..'); // Returns: '/foo/bar/baz/asdf' ``` On Windows: ```js path.normalize('C:\\temp\\\\foo\\bar\\..\\'); // Returns: 'C:\\temp\\foo\\' ``` Since Windows recognizes multiple path separators, both separators will be replaced by instances of the Windows preferred separator (`\`): ```js path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar'); // Returns: 'C:\\temp\\foo\\bar' ``` A [`TypeError`][] is thrown if `path` is not a string. ## `path.parse(path)` \* `path` {string} \* Returns: {Object} The `path.parse()` method returns an object whose properties represent significant elements of the `path`. Trailing directory separators are ignored, see [`path.sep`][]. The returned object will have the following properties: \* `dir` {string} \* `root` {string} \* `base` {string} \* `name` {string} \* `ext` {string} For example, on POSIX: ```js path.parse('/home/user/dir/file.txt'); // Returns: // { root: '/', // dir: '/home/user/dir', // base: 'file.txt', // ext: '.txt', // name: 'file' } ``` ```text ┌─────────────────────┬────────────┐ │ dir │ base │ ├──────┬ ├──────┬─────┤ │ root │ │ name │ ext │ " / home/user/dir / file .txt " └──────┴──────────────┴──────┴─────┘ (All spaces in the "" line should be ignored. They are purely for formatting.) ``` On Windows: ```js path.parse('C:\\path\\dir\\file.txt'); // Returns: // { root: 'C:\\', // dir: 'C:\\path\\dir', // base: 'file.txt', // ext: '.txt', // name: 'file' } ``` ```text ┌─────────────────────┬────────────┐ │ dir │ base │ ├──────┬ ├──────┬─────┤ │ root │ │ name │ ext │ " C:\ path\dir \ file .txt " └──────┴──────────────┴──────┴─────┘ (All spaces in the "" line should be ignored. They are purely for formatting.) ``` A [`TypeError`][] is thrown if `path` is not a string. ## `path.posix` \* Type: {Object} The `path.posix` property provides access to POSIX specific implementations of the `path` methods. The API is accessible via `require('node:path').posix` or `require('node:path/posix')`. ## `path.relative(from, to)` \* `from` {string} \* `to` {string} \* Returns: {string} The `path.relative()` method returns the relative path from `from` to `to` based on the current working directory. If `from` and `to` each resolve to the same path (after calling `path.resolve()` on each), a zero-length string is returned. If a zero-length string is passed as `from` or `to`, the current working directory will be used instead of the zero-length strings. For example, on POSIX: ```js path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); // Returns: '../../impl/bbb' ``` On Windows: ```js path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); // Returns: '..\\..\\impl\\bbb' ``` A [`TypeError`][] is thrown if either `from` or `to` is not a string. ## `path.resolve([...paths])` \* `...paths` {string} A sequence of paths or path segments \* Returns: {string} The `path.resolve()` method resolves a sequence of paths or path segments into an absolute path. The given sequence of paths is processed from right to left, with each subsequent `path` prepended until an absolute path is constructed. For instance, given the sequence of path segments: `/foo`, `/bar`, `baz`, calling `path.resolve('/foo', '/bar', 'baz')` would return `/bar/baz` because `'baz'` is not an absolute path but `'/bar' + '/' + 'baz'` is. If, after processing all given `path` segments, an absolute path has not yet been generated, the current working directory is used. The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory. Zero-length `path` segments are ignored. If no `path` segments are passed, `path.resolve()` will return the absolute path of the current working directory. ```js path.resolve('/foo/bar', './baz'); // Returns: '/foo/bar/baz' path.resolve('/foo/bar', '/tmp/file/'); // Returns: '/tmp/file' path.resolve('wwwroot', 'static\_files/png/', '../gif/image.gif'); // If the current working directory is /home/myself/node, // this | https://github.com/nodejs/node/blob/main//doc/api/path.md | main | nodejs | [
-0.036839697510004044,
0.006434490438550711,
0.04562478885054588,
0.05119699612259865,
-0.057996101677417755,
-0.050664033740758896,
-0.045485906302928925,
0.04133794084191322,
0.06321322917938232,
-0.005567651707679033,
0.03782200440764427,
0.016300177201628685,
-0.030983831733465195,
0.0... | 0.074807 |
to the root directory. Zero-length `path` segments are ignored. If no `path` segments are passed, `path.resolve()` will return the absolute path of the current working directory. ```js path.resolve('/foo/bar', './baz'); // Returns: '/foo/bar/baz' path.resolve('/foo/bar', '/tmp/file/'); // Returns: '/tmp/file' path.resolve('wwwroot', 'static\_files/png/', '../gif/image.gif'); // If the current working directory is /home/myself/node, // this returns '/home/myself/node/wwwroot/static\_files/gif/image.gif' ``` A [`TypeError`][] is thrown if any of the arguments is not a string. ## `path.sep` \* Type: {string} Provides the platform-specific path segment separator: \* `\` on Windows \* `/` on POSIX For example, on POSIX: ```js 'foo/bar/baz'.split(path.sep); // Returns: ['foo', 'bar', 'baz'] ``` On Windows: ```js 'foo\\bar\\baz'.split(path.sep); // Returns: ['foo', 'bar', 'baz'] ``` On Windows, both the forward slash (`/`) and backward slash (`\`) are accepted as path segment separators; however, the `path` methods only add backward slashes (`\`). ## `path.toNamespacedPath(path)` \* `path` {string} \* Returns: {string} On Windows systems only, returns an equivalent [namespace-prefixed path][] for the given `path`. If `path` is not a string, `path` will be returned without modifications. This method is meaningful only on Windows systems. On POSIX systems, the method is non-operational and always returns `path` without modifications. ## `path.win32` \* Type: {Object} The `path.win32` property provides access to Windows-specific implementations of the `path` methods. The API is accessible via `require('node:path').win32` or `require('node:path/win32')`. [MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths [`TypeError`]: errors.md#class-typeerror [`path.parse()`]: #pathparsepath [`path.posix`]: #pathposix [`path.sep`]: #pathsep [`path.win32`]: #pathwin32 [namespace-prefixed path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#namespaces | https://github.com/nodejs/node/blob/main//doc/api/path.md | main | nodejs | [
-0.061341121792793274,
0.007299638353288174,
0.032865140587091446,
-0.0007117980276234448,
-0.0032904965337365866,
-0.10943026840686798,
-0.01465025544166565,
0.14347538352012634,
0.0705019161105156,
-0.02662038803100586,
0.029827337712049484,
0.06697793304920197,
-0.0011234133271500468,
0... | 0.0429 |
# Worker threads > Stability: 2 - Stable The `node:worker\_threads` module enables the use of threads that execute JavaScript in parallel. To access it: ```mjs import worker\_threads from 'node:worker\_threads'; ``` ```cjs 'use strict'; const worker\_threads = require('node:worker\_threads'); ``` Workers (threads) are useful for performing CPU-intensive JavaScript operations. They do not help much with I/O-intensive work. The Node.js built-in asynchronous I/O operations are more efficient than Workers can be. Unlike `child\_process` or `cluster`, `worker\_threads` can share memory. They do so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer` instances. ```mjs import { Worker, isMainThread, parentPort, workerData, } from 'node:worker\_threads'; if (!isMainThread) { const { parse } = await import('some-js-parsing-library'); const script = workerData; parentPort.postMessage(parse(script)); } export default function parseJSAsync(script) { return new Promise((resolve, reject) => { const worker = new Worker(new URL(import.meta.url), { workerData: script, }); worker.on('message', resolve); worker.once('error', reject); worker.once('exit', (code) => { if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`)); }); }); }; ``` ```cjs 'use strict'; const { Worker, isMainThread, parentPort, workerData, } = require('node:worker\_threads'); if (isMainThread) { module.exports = function parseJSAsync(script) { return new Promise((resolve, reject) => { const worker = new Worker(\_\_filename, { workerData: script, }); worker.on('message', resolve); worker.once('error', reject); worker.once('exit', (code) => { if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`)); }); }); }; } else { const { parse } = require('some-js-parsing-library'); const script = workerData; parentPort.postMessage(parse(script)); } ``` The above example spawns a Worker thread for each `parseJSAsync()` call. In practice, use a pool of Workers for these kinds of tasks. Otherwise, the overhead of creating Workers would likely exceed their benefit. When implementing a worker pool, use the [`AsyncResource`][] API to inform diagnostic tools (e.g. to provide asynchronous stack traces) about the correlation between tasks and their outcomes. See ["Using `AsyncResource` for a `Worker` thread pool"][async-resource-worker-pool] in the `async\_hooks` documentation for an example implementation. Worker threads inherit non-process-specific options by default. Refer to [`Worker constructor options`][] to know how to customize worker thread options, specifically `argv` and `execArgv` options. ## `worker\_threads.getEnvironmentData(key)` \* `key` {any} Any arbitrary, cloneable JavaScript value that can be used as a {Map} key. \* Returns: {any} Within a worker thread, `worker.getEnvironmentData()` returns a clone of data passed to the spawning thread's `worker.setEnvironmentData()`. Every new `Worker` receives its own copy of the environment data automatically. ```mjs import { Worker, isMainThread, setEnvironmentData, getEnvironmentData, } from 'node:worker\_threads'; if (isMainThread) { setEnvironmentData('Hello', 'World!'); const worker = new Worker(new URL(import.meta.url)); } else { console.log(getEnvironmentData('Hello')); // Prints 'World!'. } ``` ```cjs 'use strict'; const { Worker, isMainThread, setEnvironmentData, getEnvironmentData, } = require('node:worker\_threads'); if (isMainThread) { setEnvironmentData('Hello', 'World!'); const worker = new Worker(\_\_filename); } else { console.log(getEnvironmentData('Hello')); // Prints 'World!'. } ``` ## `worker\_threads.isInternalThread` \* Type: {boolean} Is `true` if this code is running inside of an internal [`Worker`][] thread (e.g the loader thread). ```bash node --experimental-loader ./loader.js main.js ``` ```mjs // loader.js import { isInternalThread } from 'node:worker\_threads'; console.log(isInternalThread); // true ``` ```cjs // loader.js 'use strict'; const { isInternalThread } = require('node:worker\_threads'); console.log(isInternalThread); // true ``` ```mjs // main.js import { isInternalThread } from 'node:worker\_threads'; console.log(isInternalThread); // false ``` ```cjs // main.js 'use strict'; const { isInternalThread } = require('node:worker\_threads'); console.log(isInternalThread); // false ``` ## `worker\_threads.isMainThread` \* Type: {boolean} Is `true` if this code is not running inside of a [`Worker`][] thread. ```mjs import { Worker, isMainThread } from 'node:worker\_threads'; if (isMainThread) { // This re-loads the current file inside a Worker instance. new Worker(new URL(import.meta.url)); } else { console.log('Inside Worker!'); console.log(isMainThread); // Prints 'false'. } ``` ```cjs 'use strict'; const { Worker, isMainThread } = require('node:worker\_threads'); if (isMainThread) { // This re-loads the current file inside a | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.06924428790807724,
-0.005231431219726801,
-0.03458986431360245,
0.0959927961230278,
0.03343535214662552,
-0.10745995491743088,
-0.02814258635044098,
0.017780762165784836,
-0.014325300231575966,
-0.004209715873003006,
-0.07105681300163269,
0.08851034939289093,
-0.014046109281480312,
-0.0... | 0.206297 |
from 'node:worker\_threads'; if (isMainThread) { // This re-loads the current file inside a Worker instance. new Worker(new URL(import.meta.url)); } else { console.log('Inside Worker!'); console.log(isMainThread); // Prints 'false'. } ``` ```cjs 'use strict'; const { Worker, isMainThread } = require('node:worker\_threads'); if (isMainThread) { // This re-loads the current file inside a Worker instance. new Worker(\_\_filename); } else { console.log('Inside Worker!'); console.log(isMainThread); // Prints 'false'. } ``` ## `worker\_threads.markAsUntransferable(object)` \* `object` {any} Any arbitrary JavaScript value. Mark an object as not transferable. If `object` occurs in the transfer list of a [`port.postMessage()`][] call, an error is thrown. This is a no-op if `object` is a primitive value. In particular, this makes sense for objects that can be cloned, rather than transferred, and which are used by other objects on the sending side. For example, Node.js marks the `ArrayBuffer`s it uses for its [`Buffer` pool][`Buffer.allocUnsafe()`] with this. `ArrayBuffer.prototype.transfer()` is disallowed on such array buffer instances. This operation cannot be undone. ```mjs import { MessageChannel, markAsUntransferable } from 'node:worker\_threads'; const pooledBuffer = new ArrayBuffer(8); const typedArray1 = new Uint8Array(pooledBuffer); const typedArray2 = new Float64Array(pooledBuffer); markAsUntransferable(pooledBuffer); const { port1 } = new MessageChannel(); try { // This will throw an error, because pooledBuffer is not transferable. port1.postMessage(typedArray1, [ typedArray1.buffer ]); } catch (error) { // error.name === 'DataCloneError' } // The following line prints the contents of typedArray1 -- it still owns // its memory and has not been transferred. Without // `markAsUntransferable()`, this would print an empty Uint8Array and the // postMessage call would have succeeded. // typedArray2 is intact as well. console.log(typedArray1); console.log(typedArray2); ``` ```cjs 'use strict'; const { MessageChannel, markAsUntransferable } = require('node:worker\_threads'); const pooledBuffer = new ArrayBuffer(8); const typedArray1 = new Uint8Array(pooledBuffer); const typedArray2 = new Float64Array(pooledBuffer); markAsUntransferable(pooledBuffer); const { port1 } = new MessageChannel(); try { // This will throw an error, because pooledBuffer is not transferable. port1.postMessage(typedArray1, [ typedArray1.buffer ]); } catch (error) { // error.name === 'DataCloneError' } // The following line prints the contents of typedArray1 -- it still owns // its memory and has not been transferred. Without // `markAsUntransferable()`, this would print an empty Uint8Array and the // postMessage call would have succeeded. // typedArray2 is intact as well. console.log(typedArray1); console.log(typedArray2); ``` There is no equivalent to this API in browsers. ## `worker\_threads.isMarkedAsUntransferable(object)` \* `object` {any} Any JavaScript value. \* Returns: {boolean} Check if an object is marked as not transferable with [`markAsUntransferable()`][]. ```mjs import { markAsUntransferable, isMarkedAsUntransferable } from 'node:worker\_threads'; const pooledBuffer = new ArrayBuffer(8); markAsUntransferable(pooledBuffer); isMarkedAsUntransferable(pooledBuffer); // Returns true. ``` ```cjs 'use strict'; const { markAsUntransferable, isMarkedAsUntransferable } = require('node:worker\_threads'); const pooledBuffer = new ArrayBuffer(8); markAsUntransferable(pooledBuffer); isMarkedAsUntransferable(pooledBuffer); // Returns true. ``` There is no equivalent to this API in browsers. ## `worker\_threads.markAsUncloneable(object)` \* `object` {any} Any arbitrary JavaScript value. Mark an object as not cloneable. If `object` is used as [`message`](#event-message) in a [`port.postMessage()`][] call, an error is thrown. This is a no-op if `object` is a primitive value. This has no effect on `ArrayBuffer`, or any `Buffer` like objects. This operation cannot be undone. ```mjs import { markAsUncloneable } from 'node:worker\_threads'; const anyObject = { foo: 'bar' }; markAsUncloneable(anyObject); const { port1 } = new MessageChannel(); try { // This will throw an error, because anyObject is not cloneable. port1.postMessage(anyObject); } catch (error) { // error.name === 'DataCloneError' } ``` ```cjs 'use strict'; const { markAsUncloneable } = require('node:worker\_threads'); const anyObject = { foo: 'bar' }; markAsUncloneable(anyObject); const { port1 } = new MessageChannel(); try { // This will throw an error, because anyObject is not cloneable. port1.postMessage(anyObject); } catch (error) { // error.name === 'DataCloneError' } ``` There is no equivalent | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.09393788874149323,
0.042629193514585495,
0.01675405539572239,
0.0211953092366457,
0.08074236661195755,
-0.11331150680780411,
0.030484642833471298,
-0.021415051072835922,
0.041503019630908966,
0.02859223447740078,
-0.04416963458061218,
0.05114158242940903,
-0.09690846502780914,
-0.035171... | 0.117975 |
strict'; const { markAsUncloneable } = require('node:worker\_threads'); const anyObject = { foo: 'bar' }; markAsUncloneable(anyObject); const { port1 } = new MessageChannel(); try { // This will throw an error, because anyObject is not cloneable. port1.postMessage(anyObject); } catch (error) { // error.name === 'DataCloneError' } ``` There is no equivalent to this API in browsers. ## `worker\_threads.moveMessagePortToContext(port, contextifiedSandbox)` \* `port` {MessagePort} The message port to transfer. \* `contextifiedSandbox` {Object} A [contextified][] object as returned by the `vm.createContext()` method. \* Returns: {MessagePort} Transfer a `MessagePort` to a different [`vm`][] Context. The original `port` object is rendered unusable, and the returned `MessagePort` instance takes its place. The returned `MessagePort` is an object in the target context and inherits from its global `Object` class. Objects passed to the [`port.onmessage()`][] listener are also created in the target context and inherit from its global `Object` class. However, the created `MessagePort` no longer inherits from {EventTarget}, and only [`port.onmessage()`][] can be used to receive events using it. ## `worker\_threads.parentPort` \* Type: {null|MessagePort} If this thread is a [`Worker`][], this is a [`MessagePort`][] allowing communication with the parent thread. Messages sent using `parentPort.postMessage()` are available in the parent thread using `worker.on('message')`, and messages sent from the parent thread using `worker.postMessage()` are available in this thread using `parentPort.on('message')`. ```mjs import { Worker, isMainThread, parentPort } from 'node:worker\_threads'; if (isMainThread) { const worker = new Worker(new URL(import.meta.url)); worker.once('message', (message) => { console.log(message); // Prints 'Hello, world!'. }); worker.postMessage('Hello, world!'); } else { // When a message from the parent thread is received, send it back: parentPort.once('message', (message) => { parentPort.postMessage(message); }); } ``` ```cjs 'use strict'; const { Worker, isMainThread, parentPort } = require('node:worker\_threads'); if (isMainThread) { const worker = new Worker(\_\_filename); worker.once('message', (message) => { console.log(message); // Prints 'Hello, world!'. }); worker.postMessage('Hello, world!'); } else { // When a message from the parent thread is received, send it back: parentPort.once('message', (message) => { parentPort.postMessage(message); }); } ``` ## `worker\_threads.postMessageToThread(threadId, value[, transferList][, timeout])` > Stability: 1.1 - Active development \* `threadId` {number} The target thread ID. If the thread ID is invalid, a [`ERR\_WORKER\_MESSAGING\_FAILED`][] error will be thrown. If the target thread ID is the current thread ID, a [`ERR\_WORKER\_MESSAGING\_SAME\_THREAD`][] error will be thrown. \* `value` {any} The value to send. \* `transferList` {Object\[]} If one or more `MessagePort`-like objects are passed in `value`, a `transferList` is required for those items or [`ERR\_MISSING\_MESSAGE\_PORT\_IN\_TRANSFER\_LIST`][] is thrown. See [`port.postMessage()`][] for more information. \* `timeout` {number} Time to wait for the message to be delivered in milliseconds. By default it's `undefined`, which means wait forever. If the operation times out, a [`ERR\_WORKER\_MESSAGING\_TIMEOUT`][] error is thrown. \* Returns: {Promise} A promise which is fulfilled if the message was successfully processed by destination thread. Sends a value to another worker, identified by its thread ID. If the target thread has no listener for the `workerMessage` event, then the operation will throw a [`ERR\_WORKER\_MESSAGING\_FAILED`][] error. If the target thread threw an error while processing the `workerMessage` event, then the operation will throw a [`ERR\_WORKER\_MESSAGING\_ERRORED`][] error. This method should be used when the target thread is not the direct parent or child of the current thread. If the two threads are parent-children, use the [`require('node:worker\_threads').parentPort.postMessage()`][] and the [`worker.postMessage()`][] to let the threads communicate. The example below shows the use of of `postMessageToThread`: it creates 10 nested threads, the last one will try to communicate with the main thread. ```mjs import process from 'node:process'; import { postMessageToThread, threadId, workerData, Worker, } from 'node:worker\_threads'; const channel = new BroadcastChannel('sync'); const level = workerData?.level ?? 0; if (level < 10) { const worker = new Worker(new URL(import.meta.url), { workerData: | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.07946646958589554,
-0.028075912967324257,
-0.003909686114639044,
0.06015387922525406,
-0.007159201428294182,
-0.07562550157308578,
0.035704515874385834,
-0.013712338171899319,
-0.02046283334493637,
-0.0408206470310688,
0.005558175500482321,
-0.06900642812252045,
0.020530525594949722,
0.... | 0.161695 |
threads, the last one will try to communicate with the main thread. ```mjs import process from 'node:process'; import { postMessageToThread, threadId, workerData, Worker, } from 'node:worker\_threads'; const channel = new BroadcastChannel('sync'); const level = workerData?.level ?? 0; if (level < 10) { const worker = new Worker(new URL(import.meta.url), { workerData: { level: level + 1 }, }); } if (level === 0) { process.on('workerMessage', (value, source) => { console.log(`${source} -> ${threadId}:`, value); postMessageToThread(source, { message: 'pong' }); }); } else if (level === 10) { process.on('workerMessage', (value, source) => { console.log(`${source} -> ${threadId}:`, value); channel.postMessage('done'); channel.close(); }); await postMessageToThread(0, { message: 'ping' }); } channel.onmessage = channel.close; ``` ```cjs 'use strict'; const process = require('node:process'); const { postMessageToThread, threadId, workerData, Worker, } = require('node:worker\_threads'); const channel = new BroadcastChannel('sync'); const level = workerData?.level ?? 0; if (level < 10) { const worker = new Worker(\_\_filename, { workerData: { level: level + 1 }, }); } if (level === 0) { process.on('workerMessage', (value, source) => { console.log(`${source} -> ${threadId}:`, value); postMessageToThread(source, { message: 'pong' }); }); } else if (level === 10) { process.on('workerMessage', (value, source) => { console.log(`${source} -> ${threadId}:`, value); channel.postMessage('done'); channel.close(); }); postMessageToThread(0, { message: 'ping' }); } channel.onmessage = channel.close; ``` ## `worker\_threads.receiveMessageOnPort(port)` \* `port` {MessagePort|BroadcastChannel} \* Returns: {Object|undefined} Receive a single message from a given `MessagePort`. If no message is available, `undefined` is returned, otherwise an object with a single `message` property that contains the message payload, corresponding to the oldest message in the `MessagePort`'s queue. ```mjs import { MessageChannel, receiveMessageOnPort } from 'node:worker\_threads'; const { port1, port2 } = new MessageChannel(); port1.postMessage({ hello: 'world' }); console.log(receiveMessageOnPort(port2)); // Prints: { message: { hello: 'world' } } console.log(receiveMessageOnPort(port2)); // Prints: undefined ``` ```cjs 'use strict'; const { MessageChannel, receiveMessageOnPort } = require('node:worker\_threads'); const { port1, port2 } = new MessageChannel(); port1.postMessage({ hello: 'world' }); console.log(receiveMessageOnPort(port2)); // Prints: { message: { hello: 'world' } } console.log(receiveMessageOnPort(port2)); // Prints: undefined ``` When this function is used, no `'message'` event is emitted and the `onmessage` listener is not invoked. ## `worker\_threads.resourceLimits` \* Type: {Object} \* `maxYoungGenerationSizeMb` {number} \* `maxOldGenerationSizeMb` {number} \* `codeRangeSizeMb` {number} \* `stackSizeMb` {number} Provides the set of JS engine resource constraints inside this Worker thread. If the `resourceLimits` option was passed to the [`Worker`][] constructor, this matches its values. If this is used in the main thread, its value is an empty object. ## `worker\_threads.SHARE\_ENV` \* Type: {symbol} A special value that can be passed as the `env` option of the [`Worker`][] constructor, to indicate that the current thread and the Worker thread should share read and write access to the same set of environment variables. ```mjs import process from 'node:process'; import { Worker, SHARE\_ENV } from 'node:worker\_threads'; new Worker('process.env.SET\_IN\_WORKER = "foo"', { eval: true, env: SHARE\_ENV }) .once('exit', () => { console.log(process.env.SET\_IN\_WORKER); // Prints 'foo'. }); ``` ```cjs 'use strict'; const { Worker, SHARE\_ENV } = require('node:worker\_threads'); new Worker('process.env.SET\_IN\_WORKER = "foo"', { eval: true, env: SHARE\_ENV }) .once('exit', () => { console.log(process.env.SET\_IN\_WORKER); // Prints 'foo'. }); ``` ## `worker\_threads.setEnvironmentData(key[, value])` \* `key` {any} Any arbitrary, cloneable JavaScript value that can be used as a {Map} key. \* `value` {any} Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value for the `key` will be deleted. The `worker.setEnvironmentData()` API sets the content of `worker.getEnvironmentData()` in the current thread and all new `Worker` instances spawned from the current context. ## `worker\_threads.threadId` \* Type: {integer} An integer identifier for the current thread. On the corresponding worker object (if there is any), it | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
0.021094629541039467,
-0.022089963778853416,
0.023404790088534355,
-0.008893785066902637,
0.013354051858186722,
-0.06980487704277039,
0.026846351101994514,
-0.029070019721984863,
0.04749756306409836,
-0.027393922209739685,
-0.0656476616859436,
-0.011586746200919151,
-0.006167578510940075,
... | 0.099863 |
for the `key` will be deleted. The `worker.setEnvironmentData()` API sets the content of `worker.getEnvironmentData()` in the current thread and all new `Worker` instances spawned from the current context. ## `worker\_threads.threadId` \* Type: {integer} An integer identifier for the current thread. On the corresponding worker object (if there is any), it is available as [`worker.threadId`][]. This value is unique for each [`Worker`][] instance inside a single process. ## `worker\_threads.threadName` \* {string|null} A string identifier for the current thread or null if the thread is not running. On the corresponding worker object (if there is any), it is available as [`worker.threadName`][]. ## `worker\_threads.workerData` An arbitrary JavaScript value that contains a clone of the data passed to this thread's `Worker` constructor. The data is cloned as if using [`postMessage()`][`port.postMessage()`], according to the [HTML structured clone algorithm][]. ```mjs import { Worker, isMainThread, workerData } from 'node:worker\_threads'; if (isMainThread) { const worker = new Worker(new URL(import.meta.url), { workerData: 'Hello, world!' }); } else { console.log(workerData); // Prints 'Hello, world!'. } ``` ```cjs 'use strict'; const { Worker, isMainThread, workerData } = require('node:worker\_threads'); if (isMainThread) { const worker = new Worker(\_\_filename, { workerData: 'Hello, world!' }); } else { console.log(workerData); // Prints 'Hello, world!'. } ``` ## `worker\_threads.locks` > Stability: 1 - Experimental \* {LockManager} An instance of a [`LockManager`][LockManager] that can be used to coordinate access to resources that may be shared across multiple threads within the same process. The API mirrors the semantics of the [browser `LockManager`][] ### Class: `Lock` The `Lock` interface provides information about a lock that has been granted via [`locks.request()`][locks.request()] #### `lock.name` \* {string} The name of the lock. #### `lock.mode` \* {string} The mode of the lock. Either `shared` or `exclusive`. ### Class: `LockManager` The `LockManager` interface provides methods for requesting and introspecting locks. To obtain a `LockManager` instance use ```mjs import { locks } from 'node:worker\_threads'; ``` ```cjs 'use strict'; const { locks } = require('node:worker\_threads'); ``` This implementation matches the [browser `LockManager`][] API. #### `locks.request(name[, options], callback)` \* `name` {string} \* `options` {Object} \* `mode` {string} Either `'exclusive'` or `'shared'`. \*\*Default:\*\* `'exclusive'`. \* `ifAvailable` {boolean} If `true`, the request will only be granted if the lock is not already held. If it cannot be granted, `callback` will be invoked with `null` instead of a `Lock` instance. \*\*Default:\*\* `false`. \* `steal` {boolean} If `true`, any existing locks with the same name are released and the request is granted immediately, pre-empting any queued requests. \*\*Default:\*\* `false`. \* `signal` {AbortSignal} that can be used to abort a pending (but not yet granted) lock request. \* `callback` {Function} Invoked once the lock is granted (or immediately with `null` if `ifAvailable` is `true` and the lock is unavailable). The lock is released automatically when the function returns, or—if the function returns a promise—when that promise settles. \* Returns: {Promise} Resolves once the lock has been released. ```mjs import { locks } from 'node:worker\_threads'; await locks.request('my\_resource', async (lock) => { // The lock has been acquired. }); // The lock has been released here. ``` ```cjs 'use strict'; const { locks } = require('node:worker\_threads'); locks.request('my\_resource', async (lock) => { // The lock has been acquired. }).then(() => { // The lock has been released here. }); ``` #### `locks.query()` \* Returns: {Promise} Resolves with a `LockManagerSnapshot` describing the currently held and pending locks for the current process. ```mjs import { locks } from 'node:worker\_threads'; const snapshot = await locks.query(); for (const lock of snapshot.held) { console.log(`held lock: name ${lock.name}, mode ${lock.mode}`); } for (const pending of snapshot.pending) { console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`); } ``` ```cjs 'use strict'; const { locks } | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.10015122592449188,
0.02817448601126671,
-0.07050948590040207,
0.0026013513561338186,
-0.002131704706698656,
-0.09743355214595795,
0.05312955752015114,
-0.09257124364376068,
0.006518997717648745,
-0.010098656639456749,
-0.023340260609984398,
0.04436545819044113,
0.005166633054614067,
-0.... | 0.085994 |
for the current process. ```mjs import { locks } from 'node:worker\_threads'; const snapshot = await locks.query(); for (const lock of snapshot.held) { console.log(`held lock: name ${lock.name}, mode ${lock.mode}`); } for (const pending of snapshot.pending) { console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`); } ``` ```cjs 'use strict'; const { locks } = require('node:worker\_threads'); locks.query().then((snapshot) => { for (const lock of snapshot.held) { console.log(`held lock: name ${lock.name}, mode ${lock.mode}`); } for (const pending of snapshot.pending) { console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`); } }); ``` ## Class: `BroadcastChannel extends EventTarget` Instances of `BroadcastChannel` allow asynchronous one-to-many communication with all other `BroadcastChannel` instances bound to the same channel name. ```mjs import { isMainThread, BroadcastChannel, Worker, } from 'node:worker\_threads'; const bc = new BroadcastChannel('hello'); if (isMainThread) { let c = 0; bc.onmessage = (event) => { console.log(event.data); if (++c === 10) bc.close(); }; for (let n = 0; n < 10; n++) new Worker(new URL(import.meta.url)); } else { bc.postMessage('hello from every worker'); bc.close(); } ``` ```cjs 'use strict'; const { isMainThread, BroadcastChannel, Worker, } = require('node:worker\_threads'); const bc = new BroadcastChannel('hello'); if (isMainThread) { let c = 0; bc.onmessage = (event) => { console.log(event.data); if (++c === 10) bc.close(); }; for (let n = 0; n < 10; n++) new Worker(\_\_filename); } else { bc.postMessage('hello from every worker'); bc.close(); } ``` ### `new BroadcastChannel(name)` \* `name` {any} The name of the channel to connect to. Any JavaScript value that can be converted to a string using `` `${name}` `` is permitted. ### `broadcastChannel.close()` Closes the `BroadcastChannel` connection. ### `broadcastChannel.onmessage` \* Type: {Function} Invoked with a single `MessageEvent` argument when a message is received. ### `broadcastChannel.onmessageerror` \* Type: {Function} Invoked with a received message cannot be deserialized. ### `broadcastChannel.postMessage(message)` \* `message` {any} Any cloneable JavaScript value. ### `broadcastChannel.ref()` Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed BroadcastChannel does \_not\_ let the program exit if it's the only active handle left (the default behavior). If the port is `ref()`ed, calling `ref()` again has no effect. ### `broadcastChannel.unref()` Calling `unref()` on a BroadcastChannel allows the thread to exit if this is the only active handle in the event system. If the BroadcastChannel is already `unref()`ed calling `unref()` again has no effect. ## Class: `MessageChannel` Instances of the `worker.MessageChannel` class represent an asynchronous, two-way communications channel. The `MessageChannel` has no methods of its own. `new MessageChannel()` yields an object with `port1` and `port2` properties, which refer to linked [`MessagePort`][] instances. ```mjs import { MessageChannel } from 'node:worker\_threads'; const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log('received', message)); port2.postMessage({ foo: 'bar' }); // Prints: received { foo: 'bar' } from the `port1.on('message')` listener ``` ```cjs 'use strict'; const { MessageChannel } = require('node:worker\_threads'); const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log('received', message)); port2.postMessage({ foo: 'bar' }); // Prints: received { foo: 'bar' } from the `port1.on('message')` listener ``` ## Class: `MessagePort` \* Extends: {EventTarget} Instances of the `worker.MessagePort` class represent one end of an asynchronous, two-way communications channel. It can be used to transfer structured data, memory regions and other `MessagePort`s between different [`Worker`][]s. This implementation matches [browser `MessagePort`][]s. ### Event: `'close'` The `'close'` event is emitted once either side of the channel has been disconnected. ```mjs import { MessageChannel } from 'node:worker\_threads'; const { port1, port2 } = new MessageChannel(); // Prints: // foobar // closed! port2.on('message', (message) => console.log(message)); port2.once('close', () => console.log('closed!')); port1.postMessage('foobar'); port1.close(); ``` ```cjs 'use strict'; const { MessageChannel } = require('node:worker\_threads'); const { port1, port2 } = new MessageChannel(); // Prints: // foobar // closed! port2.on('message', (message) => console.log(message)); port2.once('close', () => console.log('closed!')); port1.postMessage('foobar'); port1.close(); | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.03581249713897705,
0.01708122529089451,
-0.03580182045698166,
0.03140454366803169,
0.02738850936293602,
-0.04769797995686531,
0.05085059255361557,
-0.026562927290797234,
0.04159014672040939,
0.03370002657175064,
-0.003290878375992179,
0.038412317633628845,
-0.0128556489944458,
-0.048231... | 0.048233 |
// Prints: // foobar // closed! port2.on('message', (message) => console.log(message)); port2.once('close', () => console.log('closed!')); port1.postMessage('foobar'); port1.close(); ``` ```cjs 'use strict'; const { MessageChannel } = require('node:worker\_threads'); const { port1, port2 } = new MessageChannel(); // Prints: // foobar // closed! port2.on('message', (message) => console.log(message)); port2.once('close', () => console.log('closed!')); port1.postMessage('foobar'); port1.close(); ``` ### Event: `'message'` \* `value` {any} The transmitted value The `'message'` event is emitted for any incoming message, containing the cloned input of [`port.postMessage()`][]. Listeners on this event receive a clone of the `value` parameter as passed to `postMessage()` and no further arguments. ### Event: `'messageerror'` \* `error` {Error} An Error object The `'messageerror'` event is emitted when deserializing a message failed. Currently, this event is emitted when there is an error occurring while instantiating the posted JS object on the receiving end. Such situations are rare, but can happen, for instance, when certain Node.js API objects are received in a `vm.Context` (where Node.js APIs are currently unavailable). ### `port.close()` Disables further sending of messages on either side of the connection. This method can be called when no further communication will happen over this `MessagePort`. The [`'close'` event][] is emitted on both `MessagePort` instances that are part of the channel. ### `port.postMessage(value[, transferList])` \* `value` {any} \* `transferList` {Object\[]} Sends a JavaScript value to the receiving side of this channel. `value` is transferred in a way which is compatible with the [HTML structured clone algorithm][]. In particular, the significant differences to `JSON` are: \* `value` may contain circular references. \* `value` may contain instances of builtin JS types such as `RegExp`s, `BigInt`s, `Map`s, `Set`s, etc. \* `value` may contain typed arrays, both using `ArrayBuffer`s and `SharedArrayBuffer`s. \* `value` may contain [`WebAssembly.Module`][] instances. \* `value` may not contain native (C++-backed) objects other than: \* {CryptoKey}s, \* {FileHandle}s, \* {Histogram}s, \* {KeyObject}s, \* {MessagePort}s, \* {net.BlockList}s, \* {net.SocketAddress}es, \* {X509Certificate}s. ```mjs import { MessageChannel } from 'node:worker\_threads'; const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log(message)); const circularData = {}; circularData.foo = circularData; // Prints: { foo: [Circular] } port2.postMessage(circularData); ``` ```cjs 'use strict'; const { MessageChannel } = require('node:worker\_threads'); const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log(message)); const circularData = {}; circularData.foo = circularData; // Prints: { foo: [Circular] } port2.postMessage(circularData); ``` `transferList` may be a list of {ArrayBuffer}, [`MessagePort`][], and [`FileHandle`][] objects. After transferring, they are not usable on the sending side of the channel anymore (even if they are not contained in `value`). Unlike with [child processes][], transferring handles such as network sockets is currently not supported. If `value` contains {SharedArrayBuffer} instances, those are accessible from either thread. They cannot be listed in `transferList`. `value` may still contain `ArrayBuffer` instances that are not in `transferList`; in that case, the underlying memory is copied rather than moved. ```mjs import { MessageChannel } from 'node:worker\_threads'; const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log(message)); const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]); // This posts a copy of `uint8Array`: port2.postMessage(uint8Array); // This does not copy data, but renders `uint8Array` unusable: port2.postMessage(uint8Array, [ uint8Array.buffer ]); // The memory for the `sharedUint8Array` is accessible from both the // original and the copy received by `.on('message')`: const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4)); port2.postMessage(sharedUint8Array); // This transfers a freshly created message port to the receiver. // This can be used, for example, to create communication channels between // multiple `Worker` threads that are children of the same parent thread. const otherChannel = new MessageChannel(); port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]); ``` ```cjs 'use strict'; const { MessageChannel } = require('node:worker\_threads'); const | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
0.007890417240560055,
0.004707548301666975,
0.007699090521782637,
0.02419242262840271,
-0.012201821431517601,
-0.05869096517562866,
0.03533677011728287,
-0.012983825989067554,
0.07326426357030869,
-0.04650415480136871,
0.02364777773618698,
-0.021324697881937027,
-0.01716841384768486,
-0.02... | 0.084677 |
to the receiver. // This can be used, for example, to create communication channels between // multiple `Worker` threads that are children of the same parent thread. const otherChannel = new MessageChannel(); port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]); ``` ```cjs 'use strict'; const { MessageChannel } = require('node:worker\_threads'); const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log(message)); const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]); // This posts a copy of `uint8Array`: port2.postMessage(uint8Array); // This does not copy data, but renders `uint8Array` unusable: port2.postMessage(uint8Array, [ uint8Array.buffer ]); // The memory for the `sharedUint8Array` is accessible from both the // original and the copy received by `.on('message')`: const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4)); port2.postMessage(sharedUint8Array); // This transfers a freshly created message port to the receiver. // This can be used, for example, to create communication channels between // multiple `Worker` threads that are children of the same parent thread. const otherChannel = new MessageChannel(); port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]); ``` The message object is cloned immediately, and can be modified after posting without having side effects. For more information on the serialization and deserialization mechanisms behind this API, see the [serialization API of the `node:v8` module][v8.serdes]. #### Considerations when transferring TypedArrays and Buffers All {TypedArray|Buffer} instances are views over an underlying {ArrayBuffer}. That is, it is the `ArrayBuffer` that actually stores the raw data while the `TypedArray` and `Buffer` objects provide a way of viewing and manipulating the data. It is possible and common for multiple views to be created over the same `ArrayBuffer` instance. Great care must be taken when using a transfer list to transfer an `ArrayBuffer` as doing so causes all `TypedArray` and `Buffer` instances that share that same `ArrayBuffer` to become unusable. ```js const ab = new ArrayBuffer(10); const u1 = new Uint8Array(ab); const u2 = new Uint16Array(ab); console.log(u2.length); // prints 5 port.postMessage(u1, [u1.buffer]); console.log(u2.length); // prints 0 ``` For `Buffer` instances, specifically, whether the underlying `ArrayBuffer` can be transferred or cloned depends entirely on how instances were created, which often cannot be reliably determined. An `ArrayBuffer` can be marked with [`markAsUntransferable()`][] to indicate that it should always be cloned and never transferred. Depending on how a `Buffer` instance was created, it may or may not own its underlying `ArrayBuffer`. An `ArrayBuffer` must not be transferred unless it is known that the `Buffer` instance owns it. In particular, for `Buffer`s created from the internal `Buffer` pool (using, for instance `Buffer.from()` or `Buffer.allocUnsafe()`), transferring them is not possible and they are always cloned, which sends a copy of the entire `Buffer` pool. This behavior may come with unintended higher memory usage and possible security concerns. See [`Buffer.allocUnsafe()`][] for more details on `Buffer` pooling. The `ArrayBuffer`s for `Buffer` instances created using `Buffer.alloc()` or `Buffer.allocUnsafeSlow()` can always be transferred but doing so renders all other existing views of those `ArrayBuffer`s unusable. #### Considerations when cloning objects with prototypes, classes, and accessors Because object cloning uses the [HTML structured clone algorithm][], non-enumerable properties, property accessors, and object prototypes are not preserved. In particular, {Buffer} objects will be read as plain {Uint8Array}s on the receiving side, and instances of JavaScript classes will be cloned as plain JavaScript objects. ```js const b = Symbol('b'); class Foo { #a = 1; constructor() { this[b] = 2; this.c = 3; } get d() { return 4; } } const { port1, port2 } = new MessageChannel(); port1.onmessage = ({ data }) => console.log(data); port2.postMessage(new Foo()); // Prints: { c: 3 } ``` This limitation extends to many built-in objects, such as the global `URL` object: ```js const | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.032594114542007446,
-0.021700533106923103,
-0.050927240401506424,
0.025504376739263535,
-0.06287913769483566,
-0.05251016095280647,
0.008638710714876652,
-0.024965785443782806,
0.00992679689079523,
-0.0639052465558052,
-0.04179712384939194,
0.008264252915978432,
-0.03747370094060898,
0.... | 0.124715 |
this.c = 3; } get d() { return 4; } } const { port1, port2 } = new MessageChannel(); port1.onmessage = ({ data }) => console.log(data); port2.postMessage(new Foo()); // Prints: { c: 3 } ``` This limitation extends to many built-in objects, such as the global `URL` object: ```js const { port1, port2 } = new MessageChannel(); port1.onmessage = ({ data }) => console.log(data); port2.postMessage(new URL('https://example.org')); // Prints: { } ``` ### `port.hasRef()` \* Returns: {boolean} If true, the `MessagePort` object will keep the Node.js event loop active. ### `port.ref()` Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port does \_not\_ let the program exit if it's the only active handle left (the default behavior). If the port is `ref()`ed, calling `ref()` again has no effect. If listeners are attached or removed using `.on('message')`, the port is `ref()`ed and `unref()`ed automatically depending on whether listeners for the event exist. ### `port.start()` Starts receiving messages on this `MessagePort`. When using this port as an event emitter, this is called automatically once `'message'` listeners are attached. This method exists for parity with the Web `MessagePort` API. In Node.js, it is only useful for ignoring messages when no event listener is present. Node.js also diverges in its handling of `.onmessage`. Setting it automatically calls `.start()`, but unsetting it lets messages queue up until a new handler is set or the port is discarded. ### `port.unref()` Calling `unref()` on a port allows the thread to exit if this is the only active handle in the event system. If the port is already `unref()`ed calling `unref()` again has no effect. If listeners are attached or removed using `.on('message')`, the port is `ref()`ed and `unref()`ed automatically depending on whether listeners for the event exist. ## Class: `Worker` \* Extends: {EventEmitter} The `Worker` class represents an independent JavaScript execution thread. Most Node.js APIs are available inside of it. Notable differences inside a Worker environment are: \* The [`process.stdin`][], [`process.stdout`][], and [`process.stderr`][] streams may be redirected by the parent thread. \* The [`require('node:worker\_threads').isMainThread`][] property is set to `false`. \* The [`require('node:worker\_threads').parentPort`][] message port is available. \* [`process.exit()`][] does not stop the whole program, just the single thread, and [`process.abort()`][] is not available. \* [`process.chdir()`][] and `process` methods that set group or user ids are not available. \* [`process.env`][] is a copy of the parent thread's environment variables, unless otherwise specified. Changes to one copy are not visible in other threads, and are not visible to native add-ons (unless [`worker.SHARE\_ENV`][] is passed as the `env` option to the [`Worker`][] constructor). On Windows, unlike the main thread, a copy of the environment variables operates in a case-sensitive manner. \* [`process.title`][] cannot be modified. \* Signals are not delivered through [`process.on('...')`][Signals events]. \* Execution may stop at any point as a result of [`worker.terminate()`][] being invoked. \* IPC channels from parent processes are not accessible. \* The [`trace\_events`][] module is not supported. \* Native add-ons can only be loaded from multiple threads if they fulfill [certain conditions][Addons worker support]. Creating `Worker` instances inside of other `Worker`s is possible. Like [Web Workers][] and the [`node:cluster` module][], two-way communication can be achieved through inter-thread message passing. Internally, a `Worker` has a built-in pair of [`MessagePort`][]s that are already associated with each other when the `Worker` is created. While the `MessagePort` object on the parent side is not directly exposed, its functionalities are exposed through [`worker.postMessage()`][] and the [`worker.on('message')`][] event on the `Worker` object for the parent thread. To create custom messaging channels (which is encouraged over using the default global channel because it facilitates separation of concerns), users can create a `MessageChannel` | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.019152797758579254,
0.005846165120601654,
0.04987422749400139,
0.0433221310377121,
0.028551097959280014,
-0.10691338777542114,
0.00554510997608304,
-0.03177507594227791,
0.09407875686883926,
-0.05114133283495903,
-0.011557957157492638,
0.04230229929089546,
-0.046693190932273865,
0.01514... | 0.076008 |
the parent side is not directly exposed, its functionalities are exposed through [`worker.postMessage()`][] and the [`worker.on('message')`][] event on the `Worker` object for the parent thread. To create custom messaging channels (which is encouraged over using the default global channel because it facilitates separation of concerns), users can create a `MessageChannel` object on either thread and pass one of the `MessagePort`s on that `MessageChannel` to the other thread through a pre-existing channel, such as the global one. See [`port.postMessage()`][] for more information on how messages are passed, and what kind of JavaScript values can be successfully transported through the thread barrier. ```mjs import assert from 'node:assert'; import { Worker, MessageChannel, MessagePort, isMainThread, parentPort, } from 'node:worker\_threads'; if (isMainThread) { const worker = new Worker(new URL(import.meta.url)); const subChannel = new MessageChannel(); worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); subChannel.port2.on('message', (value) => { console.log('received:', value); }); } else { parentPort.once('message', (value) => { assert(value.hereIsYourPort instanceof MessagePort); value.hereIsYourPort.postMessage('the worker is sending this'); value.hereIsYourPort.close(); }); } ``` ```cjs 'use strict'; const assert = require('node:assert'); const { Worker, MessageChannel, MessagePort, isMainThread, parentPort, } = require('node:worker\_threads'); if (isMainThread) { const worker = new Worker(\_\_filename); const subChannel = new MessageChannel(); worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); subChannel.port2.on('message', (value) => { console.log('received:', value); }); } else { parentPort.once('message', (value) => { assert(value.hereIsYourPort instanceof MessagePort); value.hereIsYourPort.postMessage('the worker is sending this'); value.hereIsYourPort.close(); }); } ``` ### `new Worker(filename[, options])` \* `filename` {string|URL} The path to the Worker's main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` or `data:` protocol. When using a [`data:` URL][], the data is interpreted based on MIME type using the [ECMAScript module loader][]. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path. \* `options` {Object} \* `argv` {any\[]} List of arguments which would be stringified and appended to `process.argv` in the worker. This is mostly similar to the `workerData` but the values are available on the global `process.argv` as if they were passed as CLI options to the script. \* `env` {Object} If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE\_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread's `process.env` object affect the other thread as well. \*\*Default:\*\* `process.env`. \* `eval` {boolean} If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online. \* `execArgv` {string\[]} List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this is provided as [`process.execArgv`][] inside the worker. By default, options are inherited from the parent thread. \* `stdin` {boolean} If this is set to `true`, then `worker.stdin` provides a writable stream whose contents appear as `process.stdin` inside the Worker. By default, no data is provided. \* `stdout` {boolean} If this is set to `true`, then `worker.stdout` is not automatically piped through to `process.stdout` in the parent. \* `stderr` {boolean} If this is set to `true`, then `worker.stderr` is not automatically piped through to `process.stderr` in the parent. \* `workerData` {any} Any JavaScript value that is cloned and made available as [`require('node:worker\_threads').workerData`][]. The cloning occurs as described in the [HTML structured clone algorithm][], and an error is thrown if the object cannot be cloned (e.g. because it contains `function`s). \* `trackUnmanagedFds` {boolean} If this is | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.029642529785633087,
-0.02495591714978218,
0.081180639564991,
0.045160453766584396,
0.019679896533489227,
-0.08305887877941132,
0.05566122382879257,
-0.015343447215855122,
0.055081821978092194,
-0.03439284861087799,
-0.03346298635005951,
0.039218559861183167,
-0.016622330993413925,
0.030... | 0.133099 |
in the parent. \* `workerData` {any} Any JavaScript value that is cloned and made available as [`require('node:worker\_threads').workerData`][]. The cloning occurs as described in the [HTML structured clone algorithm][], and an error is thrown if the object cannot be cloned (e.g. because it contains `function`s). \* `trackUnmanagedFds` {boolean} If this is set to `true`, then the Worker tracks raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and closes them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s. \*\*Default:\*\* `true`. \* `transferList` {Object\[]} If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR\_MISSING\_MESSAGE\_PORT\_IN\_TRANSFER\_LIST`][] is thrown. See [`port.postMessage()`][] for more information. \* `resourceLimits` {Object} An optional set of resource limits for the new JS engine instance. Reaching these limits leads to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation. \* `maxOldGenerationSizeMb` {number} The maximum size of the main heap in MB. If the command-line argument [`--max-old-space-size`][] is set, it overrides this setting. \* `maxYoungGenerationSizeMb` {number} The maximum size of a heap space for recently created objects. If the command-line argument [`--max-semi-space-size`][] is set, it overrides this setting. \* `codeRangeSizeMb` {number} The size of a pre-allocated memory range used for generated code. \* `stackSizeMb` {number} The default maximum stack size for the thread. Small values may lead to unusable Worker instances. \*\*Default:\*\* `4`. \* `name` {string} An optional `name` to be replaced in the thread name and to the worker title for debugging/identification purposes, making the final title as `[worker ${id}] ${name}`. This parameter has a maximum allowed size, depending on the operating system. If the provided name exceeds the limit, it will be truncated \* Maximum sizes: \* Windows: 32,767 characters \* macOS: 64 characters \* Linux: 16 characters \* NetBSD: limited to `PTHREAD\_MAX\_NAMELEN\_NP` \* FreeBSD and OpenBSD: limited to `MAXCOMLEN` \*\*Default:\*\* `'WorkerThread'`. ### Event: `'error'` \* `err` {any} The `'error'` event is emitted if the worker thread throws an uncaught exception. In that case, the worker is terminated. ### Event: `'exit'` \* `exitCode` {integer} The `'exit'` event is emitted once the worker has stopped. If the worker exited by calling [`process.exit()`][], the `exitCode` parameter is the passed exit code. If the worker was terminated, the `exitCode` parameter is `1`. This is the final event emitted by any `Worker` instance. ### Event: `'message'` \* `value` {any} The transmitted value The `'message'` event is emitted when the worker thread has invoked [`require('node:worker\_threads').parentPort.postMessage()`][]. See the [`port.on('message')`][] event for more details. All messages sent from the worker thread are emitted before the [`'exit'` event][] is emitted on the `Worker` object. ### Event: `'messageerror'` \* `error` {Error} An Error object The `'messageerror'` event is emitted when deserializing a message failed. ### Event: `'online'` The `'online'` event is emitted when the worker thread has started executing JavaScript code. ### `worker.cpuUsage([prev])` \* Returns: {Promise} This method returns a `Promise` that will resolve to an object identical to [`process.threadCpuUsage()`][], or reject with an [`ERR\_WORKER\_NOT\_RUNNING`][] error if the worker is no longer running. This methods allows the statistics to be observed from outside the actual thread. ### `worker.getHeapSnapshot([options])` \* `options` {Object} \* `exposeInternals` {boolean} If true, expose internals in the heap snapshot. \*\*Default:\*\* `false`. \* `exposeNumericValues` {boolean} If true, expose numeric values in artificial fields. \*\*Default:\*\* `false`. \* Returns: {Promise} A promise for a Readable Stream containing a V8 heap snapshot Returns a | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.13618117570877075,
0.017062274739146233,
-0.019977042451500893,
0.06544460356235504,
0.11287296563386917,
-0.1057901605963707,
0.05053021386265755,
-0.05911823734641075,
0.03588530048727989,
0.009922871366143227,
0.008893375284969807,
0.029162948951125145,
-0.027851136401295662,
-0.0411... | 0.223603 |
the actual thread. ### `worker.getHeapSnapshot([options])` \* `options` {Object} \* `exposeInternals` {boolean} If true, expose internals in the heap snapshot. \*\*Default:\*\* `false`. \* `exposeNumericValues` {boolean} If true, expose numeric values in artificial fields. \*\*Default:\*\* `false`. \* Returns: {Promise} A promise for a Readable Stream containing a V8 heap snapshot Returns a readable stream for a V8 snapshot of the current state of the Worker. See [`v8.getHeapSnapshot()`][] for more details. If the Worker thread is no longer running, which may occur before the [`'exit'` event][] is emitted, the returned `Promise` is rejected immediately with an [`ERR\_WORKER\_NOT\_RUNNING`][] error. ### `worker.getHeapStatistics()` \* Returns: {Promise} This method returns a `Promise` that will resolve to an object identical to [`v8.getHeapStatistics()`][], or reject with an [`ERR\_WORKER\_NOT\_RUNNING`][] error if the worker is no longer running. This methods allows the statistics to be observed from outside the actual thread. ### `worker.performance` An object that can be used to query performance information from a worker instance. #### `performance.eventLoopUtilization([utilization1[, utilization2]])` \* `utilization1` {Object} The result of a previous call to `eventLoopUtilization()`. \* `utilization2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. \* Returns: {Object} \* `idle` {number} \* `active` {number} \* `utilization` {number} The same call as [`perf\_hooks` `eventLoopUtilization()`][], except the values of the worker instance are returned. One difference is that, unlike the main thread, bootstrapping within a worker is done within the event loop. So the event loop utilization is immediately available once the worker's script begins execution. An `idle` time that does not increase does not indicate that the worker is stuck in bootstrap. The following examples shows how the worker's entire lifetime never accumulates any `idle` time, but is still be able to process messages. ```mjs import { Worker, isMainThread, parentPort } from 'node:worker\_threads'; if (isMainThread) { const worker = new Worker(new URL(import.meta.url)); setInterval(() => { worker.postMessage('hi'); console.log(worker.performance.eventLoopUtilization()); }, 100).unref(); } else { parentPort.on('message', () => console.log('msg')).unref(); (function r(n) { if (--n < 0) return; const t = Date.now(); while (Date.now() - t < 300); setImmediate(r, n); })(10); } ``` ```cjs 'use strict'; const { Worker, isMainThread, parentPort } = require('node:worker\_threads'); if (isMainThread) { const worker = new Worker(\_\_filename); setInterval(() => { worker.postMessage('hi'); console.log(worker.performance.eventLoopUtilization()); }, 100).unref(); } else { parentPort.on('message', () => console.log('msg')).unref(); (function r(n) { if (--n < 0) return; const t = Date.now(); while (Date.now() - t < 300); setImmediate(r, n); })(10); } ``` The event loop utilization of a worker is available only after the [`'online'` event][] emitted, and if called before this, or after the [`'exit'` event][], then all properties have the value of `0`. ### `worker.postMessage(value[, transferList])` \* `value` {any} \* `transferList` {Object\[]} Send a message to the worker that is received via [`require('node:worker\_threads').parentPort.on('message')`][]. See [`port.postMessage()`][] for more details. ### `worker.ref()` Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does \_not\_ let the program exit if it's the only active handle left (the default behavior). If the worker is `ref()`ed, calling `ref()` again has no effect. ### `worker.resourceLimits` \* Type: {Object} \* `maxYoungGenerationSizeMb` {number} \* `maxOldGenerationSizeMb` {number} \* `codeRangeSizeMb` {number} \* `stackSizeMb` {number} Provides the set of JS engine resource constraints for this Worker thread. If the `resourceLimits` option was passed to the [`Worker`][] constructor, this matches its values. If the worker has stopped, the return value is an empty object. ### `worker.startCpuProfile()` \* Returns: {Promise} Starting a CPU profile then return a Promise that fulfills with an error or an `CPUProfileHandle` object. This API supports `await using` syntax. ```cjs const { Worker } = require('node:worker\_threads'); const worker = new Worker(` const { parentPort } = require('worker\_threads'); parentPort.on('message', () => {}); `, { eval: true }); | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.1259980946779251,
0.07910327613353729,
0.003317215945571661,
0.0665544793009758,
0.06965648382902145,
-0.10889144241809845,
-0.04979875683784485,
-0.0045825340785086155,
0.013198455795645714,
-0.031638823449611664,
-0.0706329196691513,
-0.04318505898118019,
-0.051862504333257675,
-0.007... | 0.117306 |
Starting a CPU profile then return a Promise that fulfills with an error or an `CPUProfileHandle` object. This API supports `await using` syntax. ```cjs const { Worker } = require('node:worker\_threads'); const worker = new Worker(` const { parentPort } = require('worker\_threads'); parentPort.on('message', () => {}); `, { eval: true }); worker.on('online', async () => { const handle = await worker.startCpuProfile(); const profile = await handle.stop(); console.log(profile); worker.terminate(); }); ``` `await using` example. ```cjs const { Worker } = require('node:worker\_threads'); const w = new Worker(` const { parentPort } = require('node:worker\_threads'); parentPort.on('message', () => {}); `, { eval: true }); w.on('online', async () => { // Stop profile automatically when return and profile will be discarded await using handle = await w.startCpuProfile(); }); ``` ### `worker.startHeapProfile()` \* Returns: {Promise} Starting a Heap profile then return a Promise that fulfills with an error or an `HeapProfileHandle` object. This API supports `await using` syntax. ```cjs const { Worker } = require('node:worker\_threads'); const worker = new Worker(` const { parentPort } = require('worker\_threads'); parentPort.on('message', () => {}); `, { eval: true }); worker.on('online', async () => { const handle = await worker.startHeapProfile(); const profile = await handle.stop(); console.log(profile); worker.terminate(); }); ``` `await using` example. ```cjs const { Worker } = require('node:worker\_threads'); const w = new Worker(` const { parentPort } = require('node:worker\_threads'); parentPort.on('message', () => {}); `, { eval: true }); w.on('online', async () => { // Stop profile automatically when return and profile will be discarded await using handle = await w.startHeapProfile(); }); ``` ### `worker.stderr` \* Type: {stream.Readable} This is a readable stream which contains data written to [`process.stderr`][] inside the worker thread. If `stderr: true` was not passed to the [`Worker`][] constructor, then data is piped to the parent thread's [`process.stderr`][] stream. ### `worker.stdin` \* Type: {null|stream.Writable} If `stdin: true` was passed to the [`Worker`][] constructor, this is a writable stream. The data written to this stream will be made available in the worker thread as [`process.stdin`][]. ### `worker.stdout` \* Type: {stream.Readable} This is a readable stream which contains data written to [`process.stdout`][] inside the worker thread. If `stdout: true` was not passed to the [`Worker`][] constructor, then data is piped to the parent thread's [`process.stdout`][] stream. ### `worker.terminate()` \* Returns: {Promise} Stop all JavaScript execution in the worker thread as soon as possible. Returns a Promise for the exit code that is fulfilled when the [`'exit'` event][] is emitted. ### `worker.threadId` \* Type: {integer} An integer identifier for the referenced thread. Inside the worker thread, it is available as [`require('node:worker\_threads').threadId`][]. This value is unique for each `Worker` instance inside a single process. ### `worker.threadName` \* {string|null} A string identifier for the referenced thread or null if the thread is not running. Inside the worker thread, it is available as [`require('node:worker\_threads').threadName`][]. ### `worker.unref()` Calling `unref()` on a worker allows the thread to exit if this is the only active handle in the event system. If the worker is already `unref()`ed calling `unref()` again has no effect. ### `worker[Symbol.asyncDispose]()` Calls [`worker.terminate()`][] when the dispose scope is exited. ```js async function example() { await using worker = new Worker('for (;;) {}', { eval: true }); // Worker is automatically terminate when the scope is exited. } ``` ## Notes ### Synchronous blocking of stdio `Worker`s utilize message passing via {MessagePort} to implement interactions with `stdio`. This means that `stdio` output originating from a `Worker` can get blocked by synchronous code on the receiving end that is blocking the Node.js event loop. ```mjs import { Worker, isMainThread, } from 'node:worker\_threads'; if (isMainThread) { new Worker(new URL(import.meta.url)); for (let n = 0; n < 1e10; | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.06126270070672035,
0.052942827343940735,
-0.027728253975510597,
0.0894249677658081,
0.027798855677247047,
-0.05261122062802315,
0.014602020382881165,
0.10758428275585175,
-0.02836122177541256,
-0.051095567643642426,
-0.019854307174682617,
-0.036339256912469864,
-0.05174713954329491,
-0.... | 0.066297 |
with `stdio`. This means that `stdio` output originating from a `Worker` can get blocked by synchronous code on the receiving end that is blocking the Node.js event loop. ```mjs import { Worker, isMainThread, } from 'node:worker\_threads'; if (isMainThread) { new Worker(new URL(import.meta.url)); for (let n = 0; n < 1e10; n++) { // Looping to simulate work. } } else { // This output will be blocked by the for loop in the main thread. console.log('foo'); } ``` ```cjs 'use strict'; const { Worker, isMainThread, } = require('node:worker\_threads'); if (isMainThread) { new Worker(\_\_filename); for (let n = 0; n < 1e10; n++) { // Looping to simulate work. } } else { // This output will be blocked by the for loop in the main thread. console.log('foo'); } ``` ### Launching worker threads from preload scripts Take care when launching worker threads from preload scripts (scripts loaded and run using the `-r` command line flag). Unless the `execArgv` option is explicitly set, new Worker threads automatically inherit the command line flags from the running process and will preload the same preload scripts as the main thread. If the preload script unconditionally launches a worker thread, every thread spawned will spawn another until the application crashes. [Addons worker support]: addons.md#worker-support [ECMAScript module loader]: esm.md#data-imports [HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web\_Workers\_API/Structured\_clone\_algorithm [LockManager]: #class-lockmanager [Signals events]: process.md#signal-events [Web Workers]: https://developer.mozilla.org/en-US/docs/Web/API/Web\_Workers\_API [`'close'` event]: #event-close [`'exit'` event]: #event-exit [`'online'` event]: #event-online [`--max-old-space-size`]: cli.md#--max-old-space-sizesize-in-mib [`--max-semi-space-size`]: cli.md#--max-semi-space-sizesize-in-mib [`AsyncResource`]: async\_hooks.md#class-asyncresource [`Buffer.allocUnsafe()`]: buffer.md#static-method-bufferallocunsafesize [`ERR\_MISSING\_MESSAGE\_PORT\_IN\_TRANSFER\_LIST`]: errors.md#err\_missing\_message\_port\_in\_transfer\_list [`ERR\_WORKER\_MESSAGING\_ERRORED`]: errors.md#err\_worker\_messaging\_errored [`ERR\_WORKER\_MESSAGING\_FAILED`]: errors.md#err\_worker\_messaging\_failed [`ERR\_WORKER\_MESSAGING\_SAME\_THREAD`]: errors.md#err\_worker\_messaging\_same\_thread [`ERR\_WORKER\_MESSAGING\_TIMEOUT`]: errors.md#err\_worker\_messaging\_timeout [`ERR\_WORKER\_NOT\_RUNNING`]: errors.md#err\_worker\_not\_running [`FileHandle`]: fs.md#class-filehandle [`MessagePort`]: #class-messageport [`WebAssembly.Module`]: https://developer.mozilla.org/en-US/docs/WebAssembly/Reference/JavaScript\_interface/Module [`Worker constructor options`]: #new-workerfilename-options [`Worker`]: #class-worker [`data:` URL]: https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data [`fs.close()`]: fs.md#fsclosefd-callback [`fs.open()`]: fs.md#fsopenpath-flags-mode-callback [`markAsUntransferable()`]: #worker\_threadsmarkasuntransferableobject [`node:cluster` module]: cluster.md [`perf\_hooks` `eventLoopUtilization()`]: perf\_hooks.md#perf\_hookseventlooputilizationutilization1-utilization2 [`port.on('message')`]: #event-message [`port.onmessage()`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/message\_event [`port.postMessage()`]: #portpostmessagevalue-transferlist [`process.abort()`]: process.md#processabort [`process.chdir()`]: process.md#processchdirdirectory [`process.env`]: process.md#processenv [`process.execArgv`]: process.md#processexecargv [`process.exit()`]: process.md#processexitcode [`process.stderr`]: process.md#processstderr [`process.stdin`]: process.md#processstdin [`process.stdout`]: process.md#processstdout [`process.threadCpuUsage()`]: process.md#processthreadcpuusagepreviousvalue [`process.title`]: process.md#processtitle [`require('node:worker\_threads').isMainThread`]: #worker\_threadsismainthread [`require('node:worker\_threads').parentPort.on('message')`]: #event-message [`require('node:worker\_threads').parentPort.postMessage()`]: #workerpostmessagevalue-transferlist [`require('node:worker\_threads').parentPort`]: #worker\_threadsparentport [`require('node:worker\_threads').threadId`]: #worker\_threadsthreadid [`require('node:worker\_threads').threadName`]: #worker\_threadsthreadname [`require('node:worker\_threads').workerData`]: #worker\_threadsworkerdata [`trace\_events`]: tracing.md [`v8.getHeapSnapshot()`]: v8.md#v8getheapsnapshotoptions [`v8.getHeapStatistics()`]: v8.md#v8getheapstatistics [`vm`]: vm.md [`worker.SHARE\_ENV`]: #worker\_threadsshare\_env [`worker.on('message')`]: #event-message\_1 [`worker.postMessage()`]: #workerpostmessagevalue-transferlist [`worker.terminate()`]: #workerterminate [`worker.threadId`]: #workerthreadid [`worker.threadName`]: #workerthreadname [async-resource-worker-pool]: async\_context.md#using-asyncresource-for-a-worker-thread-pool [browser `LockManager`]: https://developer.mozilla.org/en-US/docs/Web/API/LockManager [browser `MessagePort`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort [child processes]: child\_process.md [contextified]: vm.md#what-does-it-mean-to-contextify-an-object [locks.request()]: #locksrequestname-options-callback [v8.serdes]: v8.md#serialization-api | https://github.com/nodejs/node/blob/main//doc/api/worker_threads.md | main | nodejs | [
-0.06025318056344986,
0.025810740888118744,
-0.02484099194407463,
-0.010918567888438702,
0.05048613250255585,
-0.08350397646427155,
-0.02821245789527893,
-0.031887173652648926,
0.0010812419932335615,
-0.007372522260993719,
-0.037855107337236404,
0.04561403766274452,
-0.07826334238052368,
-... | 0.112179 |
# Modules: `node:module` API ## The `Module` object \* Type: {Object} Provides general utility methods when interacting with instances of `Module`, the [`module`][] variable often seen in [CommonJS][] modules. Accessed via `import 'node:module'` or `require('node:module')`. ### `module.builtinModules` \* Type: {string\[]} A list of the names of all modules provided by Node.js. Can be used to verify if a module is maintained by a third party or not. `module` in this context isn't the same object that's provided by the [module wrapper][]. To access it, require the `Module` module: ```mjs // module.mjs // In an ECMAScript module import { builtinModules as builtin } from 'node:module'; ``` ```cjs // module.cjs // In a CommonJS module const builtin = require('node:module').builtinModules; ``` ### `module.createRequire(filename)` \* `filename` {string|URL} Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string. \* Returns: {require} Require function ```mjs import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); // sibling-module.js is a CommonJS module. const siblingModule = require('./sibling-module'); ``` ### `module.findPackageJSON(specifier[, base])` > Stability: 1.1 - Active Development \* `specifier` {string|URL} The specifier for the module whose `package.json` to retrieve. When passing a \_bare specifier\_, the `package.json` at the root of the package is returned. When passing a \_relative specifier\_ or an \_absolute specifier\_, the closest parent `package.json` is returned. \* `base` {string|URL} The absolute location (`file:` URL string or FS path) of the containing module. For CJS, use `\_\_filename` (not `\_\_dirname`!); for ESM, use `import.meta.url`. You do not need to pass it if `specifier` is an `absolute specifier`. \* Returns: {string|undefined} A path if the `package.json` is found. When `specifier` is a package, the package's root `package.json`; when a relative or unresolved, the closest `package.json` to the `specifier`. > \*\*Caveat\*\*: Do not use this to try to determine module format. There are many things affecting > that determination; the `type` field of package.json is the \_least\_ definitive (ex file extension > supersedes it, and a loader hook supersedes that). > \*\*Caveat\*\*: This currently leverages only the built-in default resolver; if > [`resolve` customization hooks][resolve hook] are registered, they will not affect the resolution. > This may change in the future. ```text /path/to/project ├ packages/ ├ bar/ ├ bar.js └ package.json // name = '@foo/bar' └ qux/ ├ node\_modules/ └ some-package/ └ package.json // name = 'some-package' ├ qux.js └ package.json // name = '@foo/qux' ├ main.js └ package.json // name = '@foo' ``` ```mjs // /path/to/project/packages/bar/bar.js import { findPackageJSON } from 'node:module'; findPackageJSON('..', import.meta.url); // '/path/to/project/package.json' // Same result when passing an absolute specifier instead: findPackageJSON(new URL('../', import.meta.url)); findPackageJSON(import.meta.resolve('../')); findPackageJSON('some-package', import.meta.url); // '/path/to/project/packages/bar/node\_modules/some-package/package.json' // When passing an absolute specifier, you might get a different result if the // resolved module is inside a subfolder that has nested `package.json`. findPackageJSON(import.meta.resolve('some-package')); // '/path/to/project/packages/bar/node\_modules/some-package/some-subfolder/package.json' findPackageJSON('@foo/qux', import.meta.url); // '/path/to/project/packages/qux/package.json' ``` ```cjs // /path/to/project/packages/bar/bar.js const { findPackageJSON } = require('node:module'); const { pathToFileURL } = require('node:url'); const path = require('node:path'); findPackageJSON('..', \_\_filename); // '/path/to/project/package.json' // Same result when passing an absolute specifier instead: findPackageJSON(pathToFileURL(path.join(\_\_dirname, '..'))); findPackageJSON('some-package', \_\_filename); // '/path/to/project/packages/bar/node\_modules/some-package/package.json' // When passing an absolute specifier, you might get a different result if the // resolved module is inside a subfolder that has nested `package.json`. findPackageJSON(pathToFileURL(require.resolve('some-package'))); // '/path/to/project/packages/bar/node\_modules/some-package/some-subfolder/package.json' findPackageJSON('@foo/qux', \_\_filename); // '/path/to/project/packages/qux/package.json' ``` ### `module.isBuiltin(moduleName)` \* `moduleName` {string} name of the module \* Returns: {boolean} returns true if the module is builtin else returns false ```mjs import { isBuiltin } from 'node:module'; isBuiltin('node:fs'); // true isBuiltin('fs'); // true isBuiltin('wss'); // false ``` ### `module.register(specifier[, parentURL][, options])` > Stability: 1.1 - Active development \* `specifier` {string|URL} Customization hooks to be registered; this should | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.071896031498909,
0.016375703737139702,
-0.022875988855957985,
0.07386341691017151,
0.0783470869064331,
-0.041144028306007385,
0.012981930747628212,
0.03838743641972542,
-0.013756604865193367,
-0.09124356508255005,
-0.00046204033424146473,
0.01436151098459959,
0.0032047443091869354,
0.02... | 0.114206 |
\* Returns: {boolean} returns true if the module is builtin else returns false ```mjs import { isBuiltin } from 'node:module'; isBuiltin('node:fs'); // true isBuiltin('fs'); // true isBuiltin('wss'); // false ``` ### `module.register(specifier[, parentURL][, options])` > Stability: 1.1 - Active development \* `specifier` {string|URL} Customization hooks to be registered; this should be the same string that would be passed to `import()`, except that if it is relative, it is resolved relative to `parentURL`. \* `parentURL` {string|URL} If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here. \*\*Default:\*\* `'data:'` \* `options` {Object} \* `parentURL` {string|URL} If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here. This property is ignored if the `parentURL` is supplied as the second argument. \*\*Default:\*\* `'data:'` \* `data` {any} Any arbitrary, cloneable JavaScript value to pass into the [`initialize`][] hook. \* `transferList` {Object\[]} [transferable objects][] to be passed into the `initialize` hook. Register a module that exports [hooks][] that customize Node.js module resolution and loading behavior. See [Customization hooks][]. This feature requires `--allow-worker` if used with the [Permission Model][]. ### `module.registerHooks(options)` > Stability: 1.2 - Release candidate \* `options` {Object} \* `load` {Function|undefined} See [load hook][]. \*\*Default:\*\* `undefined`. \* `resolve` {Function|undefined} See [resolve hook][]. \*\*Default:\*\* `undefined`. Register [hooks][] that customize Node.js module resolution and loading behavior. See [Customization hooks][]. ### `module.stripTypeScriptTypes(code[, options])` > Stability: 1.2 - Release candidate \* `code` {string} The code to strip type annotations from. \* `options` {Object} \* `mode` {string} \*\*Default:\*\* `'strip'`. Possible values are: \* `'strip'` Only strip type annotations without performing the transformation of TypeScript features. \* `'transform'` Strip type annotations and transform TypeScript features to JavaScript. \* `sourceMap` {boolean} \*\*Default:\*\* `false`. Only when `mode` is `'transform'`, if `true`, a source map will be generated for the transformed code. \* `sourceUrl` {string} Specifies the source url used in the source map. \* Returns: {string} The code with type annotations stripped. `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It can be used to strip type annotations from TypeScript code before running it with `vm.runInContext()` or `vm.compileFunction()`. By default, it will throw an error if the code contains TypeScript features that require transformation such as `Enums`, see [type-stripping][] for more information. When mode is `'transform'`, it also transforms TypeScript features to JavaScript, see [transform TypeScript features][] for more information. When mode is `'strip'`, source maps are not generated, because locations are preserved. If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown. \_WARNING\_: The output of this function should not be considered stable across Node.js versions, due to changes in the TypeScript parser. ```mjs import { stripTypeScriptTypes } from 'node:module'; const code = 'const a: number = 1;'; const strippedCode = stripTypeScriptTypes(code); console.log(strippedCode); // Prints: const a = 1; ``` ```cjs const { stripTypeScriptTypes } = require('node:module'); const code = 'const a: number = 1;'; const strippedCode = stripTypeScriptTypes(code); console.log(strippedCode); // Prints: const a = 1; ``` If `sourceUrl` is provided, it will be used appended as a comment at the end of the output: ```mjs import { stripTypeScriptTypes } from 'node:module'; const code = 'const a: number = 1;'; const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); console.log(strippedCode); // Prints: const a = 1\n\n//# sourceURL=source.ts; ``` ```cjs const { stripTypeScriptTypes } = require('node:module'); const code = 'const a: number = 1;'; const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); console.log(strippedCode); // Prints: const a = 1\n\n//# sourceURL=source.ts; ``` When `mode` is `'transform'`, the code is transformed to JavaScript: ```mjs import { stripTypeScriptTypes } from 'node:module'; const | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.05403938889503479,
0.03684446960687637,
-0.015035984106361866,
0.08045224100351334,
0.10705091804265976,
-0.0074052102863788605,
0.0171376820653677,
0.04317379742860794,
-0.0507790744304657,
0.007350016385316849,
0.0003601963398978114,
-0.05939313769340515,
0.009662581607699394,
0.03649... | 0.051947 |
{ stripTypeScriptTypes } = require('node:module'); const code = 'const a: number = 1;'; const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); console.log(strippedCode); // Prints: const a = 1\n\n//# sourceURL=source.ts; ``` When `mode` is `'transform'`, the code is transformed to JavaScript: ```mjs import { stripTypeScriptTypes } from 'node:module'; const code = ` namespace MathUtil { export const add = (a: number, b: number) => a + b; }`; const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); console.log(strippedCode); // Prints: // var MathUtil; // (function(MathUtil) { // MathUtil.add = (a, b)=>a + b; // })(MathUtil || (MathUtil = {})); // # sourceMappingURL=data:application/json;base64, ... ``` ```cjs const { stripTypeScriptTypes } = require('node:module'); const code = ` namespace MathUtil { export const add = (a: number, b: number) => a + b; }`; const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); console.log(strippedCode); // Prints: // var MathUtil; // (function(MathUtil) { // MathUtil.add = (a, b)=>a + b; // })(MathUtil || (MathUtil = {})); // # sourceMappingURL=data:application/json;base64, ... ``` ### `module.syncBuiltinESMExports()` The `module.syncBuiltinESMExports()` method updates all the live bindings for builtin [ES Modules][] to match the properties of the [CommonJS][] exports. It does not add or remove exported names from the [ES Modules][]. ```js const fs = require('node:fs'); const assert = require('node:assert'); const { syncBuiltinESMExports } = require('node:module'); fs.readFile = newAPI; delete fs.readFileSync; function newAPI() { // ... } fs.newAPI = newAPI; syncBuiltinESMExports(); import('node:fs').then((esmFS) => { // It syncs the existing readFile property with the new value assert.strictEqual(esmFS.readFile, newAPI); // readFileSync has been deleted from the required fs assert.strictEqual('readFileSync' in fs, false); // syncBuiltinESMExports() does not remove readFileSync from esmFS assert.strictEqual('readFileSync' in esmFS, true); // syncBuiltinESMExports() does not add names assert.strictEqual(esmFS.newAPI, undefined); }); ``` ## Module compile cache The module compile cache can be enabled either using the [`module.enableCompileCache()`][] method or the [`NODE\_COMPILE\_CACHE=dir`][] environment variable. After it is enabled, whenever Node.js compiles a CommonJS, a ECMAScript Module, or a TypeScript module, it will use on-disk [V8 code cache][] persisted in the specified directory to speed up the compilation. This may slow down the first load of a module graph, but subsequent loads of the same module graph may get a significant speedup if the contents of the modules do not change. To clean up the generated compile cache on disk, simply remove the cache directory. The cache directory will be recreated the next time the same directory is used for for compile cache storage. To avoid filling up the disk with stale cache, it is recommended to use a directory under the [`os.tmpdir()`][]. If the compile cache is enabled by a call to [`module.enableCompileCache()`][] without specifying the `directory`, Node.js will use the [`NODE\_COMPILE\_CACHE=dir`][] environment variable if it's set, or defaults to `path.join(os.tmpdir(), 'node-compile-cache')` otherwise. To locate the compile cache directory used by a running Node.js instance, use [`module.getCompileCacheDir()`][]. The enabled module compile cache can be disabled by the [`NODE\_DISABLE\_COMPILE\_CACHE=1`][] environment variable. This can be useful when the compile cache leads to unexpected or undesired behaviors (e.g. less precise test coverage). At the moment, when the compile cache is enabled and a module is loaded afresh, the code cache is generated from the compiled code immediately, but will only be written to disk when the Node.js instance is about to exit. This is subject to change. The [`module.flushCompileCache()`][] method can be used to ensure the accumulated code cache is flushed to disk in case the application wants to spawn other Node.js instances and let them share the cache long before the parent exits. The compile cache layout on disk is an implementation detail and should not be relied upon. The | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.08569993078708649,
0.029632598161697388,
0.062134694308042526,
0.052236590534448624,
-0.02604079246520996,
-0.009030978195369244,
0.017340587452054024,
-0.0007027690880931914,
0.03645522519946098,
-0.003940925933420658,
0.005499719642102718,
0.03283393755555153,
-0.027635719627141953,
0... | 0.046363 |
be used to ensure the accumulated code cache is flushed to disk in case the application wants to spawn other Node.js instances and let them share the cache long before the parent exits. The compile cache layout on disk is an implementation detail and should not be relied upon. The compile cache generated is typically only reusable in the same version of Node.js, and should be not assumed to be compatible across different versions of Node.js. ### Portability of the compile cache By default, caches are invalidated when the absolute paths of the modules being cached are changed. To keep the cache working after moving the project directory, enable portable compile cache. This allows previously compiled modules to be reused across different directory locations as long as the layout relative to the cache directory remains the same. This would be done on a best-effort basis. If Node.js cannot compute the location of a module relative to the cache directory, the module will not be cached. There are two ways to enable the portable mode: 1. Using the portable option in [`module.enableCompileCache()`][]: ```js // Non-portable cache (default): cache breaks if project is moved module.enableCompileCache({ directory: '/path/to/cache/storage/dir' }); // Portable cache: cache works after the project is moved module.enableCompileCache({ directory: '/path/to/cache/storage/dir', portable: true }); ``` 2. Setting the environment variable: [`NODE\_COMPILE\_CACHE\_PORTABLE=1`][] ### Limitations of the compile cache Currently when using the compile cache with [V8 JavaScript code coverage][], the coverage being collected by V8 may be less precise in functions that are deserialized from the code cache. It's recommended to turn this off when running tests to generate precise coverage. Compilation cache generated by one version of Node.js can not be reused by a different version of Node.js. Cache generated by different versions of Node.js will be stored separately if the same base directory is used to persist the cache, so they can co-exist. ### `module.constants.compileCacheStatus` The following constants are returned as the `status` field in the object returned by [`module.enableCompileCache()`][] to indicate the result of the attempt to enable the [module compile cache][]. | Constant | Description | | --- | --- | | `ENABLED` | Node.js has enabled the compile cache successfully. The directory used to store the compile cache will be returned in the `directory` field in the returned object. | | `ALREADY_ENABLED` | The compile cache has already been enabled before, either by a previous call to `module.enableCompileCache()`, or by the `NODE_COMPILE_CACHE=dir` environment variable. The directory used to store the compile cache will be returned in the `directory` field in the returned object. | | `FAILED` | Node.js fails to enable the compile cache. This can be caused by the lack of permission to use the specified directory, or various kinds of file system errors. The detail of the failure will be returned in the `message` field in the returned object. | | `DISABLED` | Node.js cannot enable the compile cache because the environment variable `NODE_DISABLE_COMPILE_CACHE=1` has been set. | ### `module.enableCompileCache([options])` \* `options` {string|Object} Optional. If a string is passed, it is considered to be `options.directory`. \* `directory` {string} Optional. Directory to store the compile cache. If not specified, the directory specified by the [`NODE\_COMPILE\_CACHE=dir`][] environment variable will be used if it's set, or `path.join(os.tmpdir(), 'node-compile-cache')` otherwise. \* `portable` {boolean} Optional. If `true`, enables portable compile cache so that the cache can be reused even if the project directory is moved. This is a best-effort feature. If not specified, it will depend on whether the environment variable [`NODE\_COMPILE\_CACHE\_PORTABLE=1`][] is set. \* Returns: {Object} \* `status` {integer} One of the [`module.constants.compileCacheStatus`][] \* `message` {string|undefined} If Node.js cannot enable | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.0400979109108448,
-0.0023512626066803932,
0.010674932040274143,
-0.01133816596120596,
0.09348291903734207,
-0.03389759361743927,
-0.051369670778512955,
0.019559727981686592,
0.06789348274469376,
0.014074415899813175,
0.02497817762196064,
0.13087482750415802,
-0.04259638115763664,
-0.032... | -0.007254 |
so that the cache can be reused even if the project directory is moved. This is a best-effort feature. If not specified, it will depend on whether the environment variable [`NODE\_COMPILE\_CACHE\_PORTABLE=1`][] is set. \* Returns: {Object} \* `status` {integer} One of the [`module.constants.compileCacheStatus`][] \* `message` {string|undefined} If Node.js cannot enable the compile cache, this contains the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`. \* `directory` {string|undefined} If the compile cache is enabled, this contains the directory where the compile cache is stored. Only set if `status` is `module.constants.compileCacheStatus.ENABLED` or `module.constants.compileCacheStatus.ALREADY\_ENABLED`. Enable [module compile cache][] in the current Node.js instance. For general use cases, it's recommended to call `module.enableCompileCache()` without specifying the `options.directory`, so that the directory can be overridden by the `NODE\_COMPILE\_CACHE` environment variable when necessary. Since compile cache is supposed to be a optimization that is not mission critical, this method is designed to not throw any exception when the compile cache cannot be enabled. Instead, it will return an object containing an error message in the `message` field to aid debugging. If compile cache is enabled successfully, the `directory` field in the returned object contains the path to the directory where the compile cache is stored. The `status` field in the returned object would be one of the `module.constants.compileCacheStatus` values to indicate the result of the attempt to enable the [module compile cache][]. This method only affects the current Node.js instance. To enable it in child worker threads, either call this method in child worker threads too, or set the `process.env.NODE\_COMPILE\_CACHE` value to compile cache directory so the behavior can be inherited into the child workers. The directory can be obtained either from the `directory` field returned by this method, or with [`module.getCompileCacheDir()`][]. ### `module.flushCompileCache()` Flush the [module compile cache][] accumulated from modules already loaded in the current Node.js instance to disk. This returns after all the flushing file system operations come to an end, no matter they succeed or not. If there are any errors, this will fail silently, since compile cache misses should not interfere with the actual operation of the application. ### `module.getCompileCacheDir()` \* Returns: {string|undefined} Path to the [module compile cache][] directory if it is enabled, or `undefined` otherwise. ## Customization Hooks Node.js currently supports two types of module customization hooks: 1. [`module.registerHooks(options)`][`module.registerHooks()`]: takes synchronous hook functions that are run directly on the thread where the modules are loaded. 2. [`module.register(specifier[, parentURL][, options])`][`register`]: takes specifier to a module that exports asynchronous hook functions. The functions are run on a separate loader thread. The asynchronous hooks incur extra overhead from inter-thread communication, and have [several caveats][caveats of asynchronous customization hooks] especially when customizing CommonJS modules in the module graph. In most cases, it's recommended to use synchronous hooks via `module.registerHooks()` for simplicity. ### Synchronous customization hooks > Stability: 1.2 - Release candidate #### Registration of synchronous customization hooks To register synchronous customization hooks, use [`module.registerHooks()`][], which takes [synchronous hook functions][] directly in-line. ```mjs // register-hooks.js import { registerHooks } from 'node:module'; registerHooks({ resolve(specifier, context, nextResolve) { /\* implementation \*/ }, load(url, context, nextLoad) { /\* implementation \*/ }, }); ``` ```cjs // register-hooks.js const { registerHooks } = require('node:module'); registerHooks({ resolve(specifier, context, nextResolve) { /\* implementation \*/ }, load(url, context, nextLoad) { /\* implementation \*/ }, }); ``` ##### Registering hooks before application code runs with flags The hooks can be registered before the application code is run by using the [`--import`][] or [`--require`][] flag: ```bash node --import ./register-hooks.js ./my-app.js node --require ./register-hooks.js ./my-app.js ``` The specifier passed to `--import` or `--require` can also come from a package: ```bash node --import some-package/register ./my-app.js node | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.01953488029539585,
0.04700475558638573,
-0.01026102714240551,
0.034022267907857895,
0.05315360426902771,
-0.026500312611460686,
0.02268681675195694,
0.000021641057173837908,
0.04426390677690506,
-0.01264934428036213,
0.018504440784454346,
0.08731493353843689,
-0.053214531391859055,
-0.0... | 0.08801 |
runs with flags The hooks can be registered before the application code is run by using the [`--import`][] or [`--require`][] flag: ```bash node --import ./register-hooks.js ./my-app.js node --require ./register-hooks.js ./my-app.js ``` The specifier passed to `--import` or `--require` can also come from a package: ```bash node --import some-package/register ./my-app.js node --require some-package/register ./my-app.js ``` Where `some-package` has an [`"exports"`][] field defining the `/register` export to map to a file that calls `registerHooks()`, like the `register-hooks.js` examples above. Using `--import` or `--require` ensures that the hooks are registered before any application code is loaded, including the entry point of the application and for any worker threads by default as well. ##### Registering hooks before application code runs programmatically Alternatively, `registerHooks()` can be called from the entry point. If the entry point needs to load other modules and the loading process needs to be customized, load them using either `require()` or dynamic `import()` after the hooks are registered. Do not use static `import` statements to load modules that need to be customized in the same module that registers the hooks, because static `import` statements are evaluated before any code in the importer module is run, including the call to `registerHooks()`, regardless of where the static `import` statements appear in the importer module. ```mjs import { registerHooks } from 'node:module'; registerHooks({ /\* implementation of synchronous hooks \*/ }); // If loaded using static import, the hooks would not be applied when loading // my-app.mjs, because statically imported modules are all executed before its // importer regardless of where the static import appears. // import './my-app.mjs'; // my-app.mjs must be loaded dynamically to ensure the hooks are applied. await import('./my-app.mjs'); ``` ```cjs const { registerHooks } = require('node:module'); registerHooks({ /\* implementation of synchronous hooks \*/ }); import('./my-app.mjs'); // Or, if my-app.mjs does not have top-level await or it's a CommonJS module, // require() can also be used: // require('./my-app.mjs'); ``` ##### Registering hooks before application code runs with a `data:` URL Alternatively, inline JavaScript code can be embedded in `data:` URLs to register the hooks before the application code runs. For example, ```bash node --import 'data:text/javascript,import {registerHooks} from "node:module"; registerHooks(/\* hooks code \*/);' ./my-app.js ``` #### Convention of hooks and chaining Hooks are part of a chain, even if that chain consists of only one custom (user-provided) hook and the default hook, which is always present. Hook functions nest: each one must always return a plain object, and chaining happens as a result of each function calling `next()`, which is a reference to the subsequent loader's hook (in LIFO order). It's possible to call `registerHooks()` more than once: ```mjs // entrypoint.mjs import { registerHooks } from 'node:module'; const hook1 = { /\* implementation of hooks \*/ }; const hook2 = { /\* implementation of hooks \*/ }; // hook2 runs before hook1. registerHooks(hook1); registerHooks(hook2); ``` ```cjs // entrypoint.cjs const { registerHooks } = require('node:module'); const hook1 = { /\* implementation of hooks \*/ }; const hook2 = { /\* implementation of hooks \*/ }; // hook2 runs before hook1. registerHooks(hook1); registerHooks(hook2); ``` In this example, the registered hooks will form chains. These chains run last-in, first-out (LIFO). If both `hook1` and `hook2` define a `resolve` hook, they will be called like so (note the right-to-left, starting with `hook2.resolve`, then `hook1.resolve`, then the Node.js default): Node.js default `resolve` ← `hook1.resolve` ← `hook2.resolve` The same applies to all the other hooks. A hook that returns a value lacking a required property triggers an exception. A hook that returns without calling `next()` \_and\_ without returning `shortCircuit: true` also triggers an exception. These errors are to help prevent | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.05425048992037773,
-0.04401400685310364,
-0.036075443029403687,
0.029616935178637505,
0.06462888419628143,
-0.005396721884608269,
0.04524461179971695,
0.03445329889655113,
0.006791388615965843,
-0.020134873688220978,
-0.040169600397348404,
0.010811759158968925,
-0.016461241990327835,
-0... | 0.087519 |
Node.js default `resolve` ← `hook1.resolve` ← `hook2.resolve` The same applies to all the other hooks. A hook that returns a value lacking a required property triggers an exception. A hook that returns without calling `next()` \_and\_ without returning `shortCircuit: true` also triggers an exception. These errors are to help prevent unintentional breaks in the chain. Return `shortCircuit: true` from a hook to signal that the chain is intentionally ending at your hook. If a hook should be applied when loading other hook modules, the other hook modules should be loaded after the hook is registered. #### Hook functions accepted by `module.registerHooks()` The `module.registerHooks()` method accepts the following synchronous hook functions. ```mjs function resolve(specifier, context, nextResolve) { // Take an `import` or `require` specifier and resolve it to a URL. } function load(url, context, nextLoad) { // Take a resolved URL and return the source code to be evaluated. } ``` Synchronous hooks are run in the same thread and the same [realm][] where the modules are loaded, the code in the hook function can pass values to the modules being referenced directly via global variables or other shared states. Unlike the asynchronous hooks, the synchronous hooks are not inherited into child worker threads by default, though if the hooks are registered using a file preloaded by [`--import`][] or [`--require`][], child worker threads can inherit the preloaded scripts via `process.execArgv` inheritance. See [the documentation of `Worker`][] for details. #### Synchronous `resolve(specifier, context, nextResolve)` \* `specifier` {string} \* `context` {Object} \* `conditions` {string\[]} Export conditions of the relevant `package.json` \* `importAttributes` {Object} An object whose key-value pairs represent the attributes for the module to import \* `parentURL` {string|undefined} The module importing this one, or undefined if this is the Node.js entry point \* `nextResolve` {Function} The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied `resolve` hook \* `specifier` {string} \* `context` {Object|undefined} When omitted, the defaults are provided. When provided, defaults are merged in with preference to the provided properties. \* Returns: {Object} \* `format` {string|null|undefined} A hint to the `load` hook (it might be ignored). It can be a module format (such as `'commonjs'` or `'module'`) or an arbitrary value like `'css'` or `'yaml'`. \* `importAttributes` {Object|undefined} The import attributes to use when caching the module (optional; if excluded the input will be used) \* `shortCircuit` {undefined|boolean} A signal that this hook intends to terminate the chain of `resolve` hooks. \*\*Default:\*\* `false` \* `url` {string} The absolute URL to which this input resolves The `resolve` hook chain is responsible for telling Node.js where to find and how to cache a given `import` statement or expression, or `require` call. It can optionally return a format (such as `'module'`) as a hint to the `load` hook. If a format is specified, the `load` hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`); if `resolve` provides a `format`, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook. Import type attributes are part of the cache key for saving loaded modules into the internal module cache. The `resolve` hook is responsible for returning an `importAttributes` object if the module should be cached with different attributes than were present in the source code. The `conditions` property in `context` is an array of conditions that will be used to match [package exports conditions][Conditional exports] for this resolution request. They can be used for looking up conditional mappings elsewhere or to modify the list when calling the default | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.07186700403690338,
-0.007692386396229267,
0.0986851155757904,
0.03844648599624634,
-0.027646036818623543,
-0.038449570536613464,
-0.0835733413696289,
0.051741328090429306,
0.03943528234958649,
-0.032156795263290405,
-0.011830616742372513,
0.03324728086590767,
0.000619910133536905,
-0.07... | 0.024596 |
than were present in the source code. The `conditions` property in `context` is an array of conditions that will be used to match [package exports conditions][Conditional exports] for this resolution request. They can be used for looking up conditional mappings elsewhere or to modify the list when calling the default resolution logic. The current [package exports conditions][Conditional exports] are always in the `context.conditions` array passed into the hook. To guarantee \_default Node.js module specifier resolution behavior\_ when calling `defaultResolve`, the `context.conditions` array passed to it \_must\_ include \_all\_ elements of the `context.conditions` array originally passed into the `resolve` hook. ```mjs import { registerHooks } from 'node:module'; function resolve(specifier, context, nextResolve) { // When calling `defaultResolve`, the arguments can be modified. For example, // to change the specifier or to add applicable export conditions. if (specifier.includes('foo')) { specifier = specifier.replace('foo', 'bar'); return nextResolve(specifier, { ...context, conditions: [...context.conditions, 'another-condition'], }); } // The hook can also skip default resolution and provide a custom URL. if (specifier === 'special-module') { return { url: 'file:///path/to/special-module.mjs', format: 'module', shortCircuit: true, // This is mandatory if nextResolve() is not called. }; } // If no customization is needed, defer to the next hook in the chain which would be the // Node.js default resolve if this is the last user-specified loader. return nextResolve(specifier); } registerHooks({ resolve }); ``` #### Synchronous `load(url, context, nextLoad)` \* `url` {string} The URL returned by the `resolve` chain \* `context` {Object} \* `conditions` {string\[]} Export conditions of the relevant `package.json` \* `format` {string|null|undefined} The format optionally supplied by the `resolve` hook chain. This can be any string value as an input; input values do not need to conform to the list of acceptable return values described below. \* `importAttributes` {Object} \* `nextLoad` {Function} The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook \* `url` {string} \* `context` {Object|undefined} When omitted, defaults are provided. When provided, defaults are merged in with preference to the provided properties. In the default `nextLoad`, if the module pointed to by `url` does not have explicit module type information, `context.format` is mandatory. \* Returns: {Object} \* `format` {string} One of the acceptable module formats listed [below][accepted final formats]. \* `shortCircuit` {undefined|boolean} A signal that this hook intends to terminate the chain of `load` hooks. \*\*Default:\*\* `false` \* `source` {string|ArrayBuffer|TypedArray} The source for Node.js to evaluate The `load` hook provides a way to define a custom method for retrieving the source code of a resolved URL. This would allow a loader to potentially avoid reading files from disk. It could also be used to map an unrecognized format to a supported one, for example `yaml` to `module`. ```mjs import { registerHooks } from 'node:module'; import { Buffer } from 'node:buffer'; function load(url, context, nextLoad) { // The hook can skip default loading and provide a custom source code. if (url === 'special-module') { return { source: 'export const special = 42;', format: 'module', shortCircuit: true, // This is mandatory if nextLoad() is not called. }; } // It's possible to modify the source code loaded by the next - possibly default - step, // for example, replacing 'foo' with 'bar' in the source code of the module. const result = nextLoad(url, context); const source = typeof result.source === 'string' ? result.source : Buffer.from(result.source).toString('utf8'); return { source: source.replace(/foo/g, 'bar'), ...result, }; } registerHooks({ resolve }); ``` In a more advanced scenario, this can also be used to transform an unsupported source to a supported one (see [Examples](#examples) below). ##### Accepted final formats returned by `load` The final value of | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.06058681011199951,
0.059770114719867706,
0.06597154587507248,
0.0037947725504636765,
0.02642357163131237,
-0.011276043951511383,
-0.016525693237781525,
0.08789890259504318,
0.0058234320022165775,
0.00702274264767766,
0.00482212333008647,
-0.05773637816309929,
0.023207437247037888,
-0.02... | 0.068777 |
'string' ? result.source : Buffer.from(result.source).toString('utf8'); return { source: source.replace(/foo/g, 'bar'), ...result, }; } registerHooks({ resolve }); ``` In a more advanced scenario, this can also be used to transform an unsupported source to a supported one (see [Examples](#examples) below). ##### Accepted final formats returned by `load` The final value of `format` must be one of the following: | `format` | Description | Acceptable types for `source` returned by `load` | | ----------------------- | ----------------------------------------------------- | -------------------------------------------------- | | `'addon'` | Load a Node.js addon | {null} | | `'builtin'` | Load a Node.js builtin module | {null} | | `'commonjs-typescript'` | Load a Node.js CommonJS module with TypeScript syntax | {string\|ArrayBuffer\|TypedArray\|null\|undefined} | | `'commonjs'` | Load a Node.js CommonJS module | {string\|ArrayBuffer\|TypedArray\|null\|undefined} | | `'json'` | Load a JSON file | {string\|ArrayBuffer\|TypedArray} | | `'module-typescript'` | Load an ES module with TypeScript syntax | {string\|ArrayBuffer\|TypedArray} | | `'module'` | Load an ES module | {string\|ArrayBuffer\|TypedArray} | | `'wasm'` | Load a WebAssembly module | {ArrayBuffer\|TypedArray} | The value of `source` is ignored for format `'builtin'` because currently it is not possible to replace the value of a Node.js builtin (core) module. > These types all correspond to classes defined in ECMAScript. \* The specific {ArrayBuffer} object is a {SharedArrayBuffer}. \* The specific {TypedArray} object is a {Uint8Array}. If the source value of a text-based format (i.e., `'json'`, `'module'`) is not a string, it is converted to a string using [`util.TextDecoder`][]. ### Asynchronous customization hooks > Stability: 1.1 - Active Development #### Caveats of asynchronous customization hooks The asynchronous customization hooks have many caveats and it is uncertain if their issues can be resolved. Users are encouraged to use the synchronous customization hooks via `module.registerHooks()` instead to avoid these caveats. \* Asynchronous hooks run on a separate thread, so the hook functions cannot directly mutate the global state of the modules being customized. It's typical to use message channels and atomics to pass data between the two or to affect control flows. See [Communication with asynchronous module customization hooks](#communication-with-asynchronous-module-customization-hooks). \* Asynchronous hooks do not affect all `require()` calls in the module graph. \* Custom `require` functions created using `module.createRequire()` are not affected. \* If the asynchronous `load` hook does not override the `source` for CommonJS modules that go through it, the child modules loaded by those CommonJS modules via built-in `require()` would not be affected by the asynchronous hooks either. \* There are several caveats that the asynchronous hooks need to handle when customizing CommonJS modules. See [asynchronous `resolve` hook][] and [asynchronous `load` hook][] for details. \* When `require()` calls inside CommonJS modules are customized by asynchronous hooks, Node.js may need to load the source code of the CommonJS module multiple times to maintain compatibility with existing CommonJS monkey-patching. If the module code changes between loads, this may lead to unexpected behaviors. \* As a side effect, if both asynchronous hooks and synchronous hooks are registered and the asynchronous hooks choose to customize the CommonJS module, the synchronous hooks may be invoked multiple times for the `require()` calls in that CommonJS module. #### Registration of asynchronous customization hooks Asynchronous customization hooks are registered using [`module.register()`][`register`] which takes a path or URL to another module that exports the [asynchronous hook functions][]. Similar to `registerHooks()`, `register()` can be called in a module preloaded by `--import` or `--require`, or called directly within the entry point. ```mjs // Use module.register() to register asynchronous hooks in a dedicated thread. import { register } from 'node:module'; register('./hooks.mjs', import.meta.url); // If my-app.mjs is loaded statically here as `import './my-app.mjs'`, since ESM // dependencies are evaluated before the module | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.05337681248784065,
0.0421660915017128,
0.005812241695821285,
0.027884624898433685,
-0.13721486926078796,
0.022107912227511406,
-0.03196217119693756,
0.062407515943050385,
0.027209660038352013,
-0.02857283130288124,
-0.101639524102211,
-0.07073860615491867,
-0.006670194678008556,
-0.0591... | -0.000063 |
by `--import` or `--require`, or called directly within the entry point. ```mjs // Use module.register() to register asynchronous hooks in a dedicated thread. import { register } from 'node:module'; register('./hooks.mjs', import.meta.url); // If my-app.mjs is loaded statically here as `import './my-app.mjs'`, since ESM // dependencies are evaluated before the module that imports them, // it's loaded \_before\_ the hooks are registered above and won't be affected. // To ensure the hooks are applied, dynamic import() must be used to load ESM // after the hooks are registered. import('./my-app.mjs'); ``` ```cjs const { register } = require('node:module'); const { pathToFileURL } = require('node:url'); // Use module.register() to register asynchronous hooks in a dedicated thread. register('./hooks.mjs', pathToFileURL(\_\_filename)); import('./my-app.mjs'); ``` In `hooks.mjs`: ```mjs // hooks.mjs export async function resolve(specifier, context, nextResolve) { /\* implementation \*/ } export async function load(url, context, nextLoad) { /\* implementation \*/ } ``` Unlike synchronous hooks, the asynchronous hooks would not run for these modules loaded in the file that calls `register()`: ```mjs // register-hooks.js import { register, createRequire } from 'node:module'; register('./hooks.mjs', import.meta.url); // Asynchronous hooks does not affect modules loaded via custom require() // functions created by module.createRequire(). const userRequire = createRequire(\_\_filename); userRequire('./my-app-2.cjs'); // Hooks won't affect this ``` ```cjs // register-hooks.js const { register, createRequire } = require('node:module'); const { pathToFileURL } = require('node:url'); register('./hooks.mjs', pathToFileURL(\_\_filename)); // Asynchronous hooks does not affect modules loaded via built-in require() // in the module calling `register()` require('./my-app-2.cjs'); // Hooks won't affect this // .. or custom require() functions created by module.createRequire(). const userRequire = createRequire(\_\_filename); userRequire('./my-app-3.cjs'); // Hooks won't affect this ``` Asynchronous hooks can also be registered using a `data:` URL with the `--import` flag: ```bash node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("my-instrumentation", pathToFileURL("./"));' ./my-app.js ``` #### Chaining of asynchronous customization hooks Chaining of `register()` work similarly to `registerHooks()`. If synchronous and asynchronous hooks are mixed, the synchronous hooks are always run first before the asynchronous hooks start running, that is, in the last synchronous hook being run, its next hook includes invocation of the asynchronous hooks. ```mjs // entrypoint.mjs import { register } from 'node:module'; register('./foo.mjs', import.meta.url); register('./bar.mjs', import.meta.url); await import('./my-app.mjs'); ``` ```cjs // entrypoint.cjs const { register } = require('node:module'); const { pathToFileURL } = require('node:url'); const parentURL = pathToFileURL(\_\_filename); register('./foo.mjs', parentURL); register('./bar.mjs', parentURL); import('./my-app.mjs'); ``` If `foo.mjs` and `bar.mjs` define a `resolve` hook, they will be called like so (note the right-to-left, starting with `./bar.mjs`, then `./foo.mjs`, then the Node.js default): Node.js default ← `./foo.mjs` ← `./bar.mjs` When using the asynchronous hooks, the registered hooks also affect subsequent `register` calls, which takes care of loading hook modules. In the example above, `bar.mjs` will be resolved and loaded via the hooks registered by `foo.mjs` (because `foo`'s hooks will have already been added to the chain). This allows for things like writing hooks in non-JavaScript languages, so long as earlier registered hooks transpile into JavaScript. The `register()` method cannot be called from the thread running the hook module that exports the asynchronous hooks or its dependencies. #### Communication with asynchronous module customization hooks Asynchronous hooks run on a dedicated thread, separate from the main thread that runs application code. This means mutating global variables won't affect the other thread(s), and message channels must be used to communicate between the threads. The `register` method can be used to pass data to an [`initialize`][] hook. The data passed to the hook may include transferable objects like ports. ```mjs import { register } from 'node:module'; import { MessageChannel } from 'node:worker\_threads'; // This example demonstrates how a message channel can be | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.043172020465135574,
-0.033268142491579056,
0.010907852090895176,
0.04576793313026428,
0.0377214178442955,
-0.02994409389793873,
-0.005029828287661076,
0.06184530258178711,
-0.04099734127521515,
-0.02674667350947857,
-0.010971431620419025,
-0.012223221361637115,
0.013662870042026043,
-0.... | 0.067528 |
the threads. The `register` method can be used to pass data to an [`initialize`][] hook. The data passed to the hook may include transferable objects like ports. ```mjs import { register } from 'node:module'; import { MessageChannel } from 'node:worker\_threads'; // This example demonstrates how a message channel can be used to // communicate with the hooks, by sending `port2` to the hooks. const { port1, port2 } = new MessageChannel(); port1.on('message', (msg) => { console.log(msg); }); port1.unref(); register('./my-hooks.mjs', { parentURL: import.meta.url, data: { number: 1, port: port2 }, transferList: [port2], }); ``` ```cjs const { register } = require('node:module'); const { pathToFileURL } = require('node:url'); const { MessageChannel } = require('node:worker\_threads'); // This example showcases how a message channel can be used to // communicate with the hooks, by sending `port2` to the hooks. const { port1, port2 } = new MessageChannel(); port1.on('message', (msg) => { console.log(msg); }); port1.unref(); register('./my-hooks.mjs', { parentURL: pathToFileURL(\_\_filename), data: { number: 1, port: port2 }, transferList: [port2], }); ``` #### Asynchronous hooks accepted by `module.register()` The [`register`][] method can be used to register a module that exports a set of hooks. The hooks are functions that are called by Node.js to customize the module resolution and loading process. The exported functions must have specific names and signatures, and they must be exported as named exports. ```mjs export async function initialize({ number, port }) { // Receives data from `register`. } export async function resolve(specifier, context, nextResolve) { // Take an `import` or `require` specifier and resolve it to a URL. } export async function load(url, context, nextLoad) { // Take a resolved URL and return the source code to be evaluated. } ``` Asynchronous hooks are run in a separate thread, isolated from the main thread where application code runs. That means it is a different [realm][]. The hooks thread may be terminated by the main thread at any time, so do not depend on asynchronous operations (like `console.log`) to complete. They are inherited into child workers by default. #### `initialize()` \* `data` {any} The data from `register(loader, import.meta.url, { data })`. The `initialize` hook is only accepted by [`register`][]. `registerHooks()` does not support nor need it since initialization done for synchronous hooks can be run directly before the call to `registerHooks()`. The `initialize` hook provides a way to define a custom function that runs in the hooks thread when the hooks module is initialized. Initialization happens when the hooks module is registered via [`register`][]. This hook can receive data from a [`register`][] invocation, including ports and other transferable objects. The return value of `initialize` can be a {Promise}, in which case it will be awaited before the main application thread execution resumes. Module customization code: ```mjs // path-to-my-hooks.js export async function initialize({ number, port }) { port.postMessage(`increment: ${number + 1}`); } ``` Caller code: ```mjs import assert from 'node:assert'; import { register } from 'node:module'; import { MessageChannel } from 'node:worker\_threads'; // This example showcases how a message channel can be used to communicate // between the main (application) thread and the hooks running on the hooks // thread, by sending `port2` to the `initialize` hook. const { port1, port2 } = new MessageChannel(); port1.on('message', (msg) => { assert.strictEqual(msg, 'increment: 2'); }); port1.unref(); register('./path-to-my-hooks.js', { parentURL: import.meta.url, data: { number: 1, port: port2 }, transferList: [port2], }); ``` ```cjs const assert = require('node:assert'); const { register } = require('node:module'); const { pathToFileURL } = require('node:url'); const { MessageChannel } = require('node:worker\_threads'); // This example showcases how a message channel can be used to communicate // between the main (application) thread and the hooks | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.014168789610266685,
-0.024161560460925102,
-0.003916206303983927,
0.07985830307006836,
-0.02166622318327427,
-0.0533439926803112,
0.056684453040361404,
0.0315263569355011,
-0.018227163702249527,
-0.04930869862437248,
-0.016360050067305565,
-0.001171223702840507,
-0.03730389475822449,
0.... | 0.123408 |
}, transferList: [port2], }); ``` ```cjs const assert = require('node:assert'); const { register } = require('node:module'); const { pathToFileURL } = require('node:url'); const { MessageChannel } = require('node:worker\_threads'); // This example showcases how a message channel can be used to communicate // between the main (application) thread and the hooks running on the hooks // thread, by sending `port2` to the `initialize` hook. const { port1, port2 } = new MessageChannel(); port1.on('message', (msg) => { assert.strictEqual(msg, 'increment: 2'); }); port1.unref(); register('./path-to-my-hooks.js', { parentURL: pathToFileURL(\_\_filename), data: { number: 1, port: port2 }, transferList: [port2], }); ``` #### Asynchronous `resolve(specifier, context, nextResolve)` \* `specifier` {string} \* `context` {Object} \* `conditions` {string\[]} Export conditions of the relevant `package.json` \* `importAttributes` {Object} An object whose key-value pairs represent the attributes for the module to import \* `parentURL` {string|undefined} The module importing this one, or undefined if this is the Node.js entry point \* `nextResolve` {Function} The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied `resolve` hook \* `specifier` {string} \* `context` {Object|undefined} When omitted, the defaults are provided. When provided, defaults are merged in with preference to the provided properties. \* Returns: {Object|Promise} The asynchronous version takes either an object containing the following properties, or a `Promise` that will resolve to such an object. \* `format` {string|null|undefined} A hint to the `load` hook (it might be ignored). It can be a module format (such as `'commonjs'` or `'module'`) or an arbitrary value like `'css'` or `'yaml'`. \* `importAttributes` {Object|undefined} The import attributes to use when caching the module (optional; if excluded the input will be used) \* `shortCircuit` {undefined|boolean} A signal that this hook intends to terminate the chain of `resolve` hooks. \*\*Default:\*\* `false` \* `url` {string} The absolute URL to which this input resolves The asynchronous version works similarly to the synchronous version, only that the `nextResolve` function returns a `Promise`, and the `resolve` hook itself can return a `Promise`. > \*\*Warning\*\* In the case of the asynchronous version, despite support for returning > promises and async functions, calls to `resolve` may still block the main thread which > can impact performance. > \*\*Warning\*\* The `resolve` hook invoked for `require()` calls inside CommonJS modules > customized by asynchronous hooks does not receive the original specifier passed to > `require()`. Instead, it receives a URL already fully resolved using the default > CommonJS resolution. > \*\*Warning\*\* In the CommonJS modules that are customized by the asynchronous customization hooks, > `require.resolve()` and `require()` will use `"import"` export condition instead of > `"require"`, which may cause unexpected behaviors when loading dual packages. ```mjs export async function resolve(specifier, context, nextResolve) { // When calling `defaultResolve`, the arguments can be modified. For example, // to change the specifier or add conditions. if (specifier.includes('foo')) { specifier = specifier.replace('foo', 'bar'); return nextResolve(specifier, { ...context, conditions: [...context.conditions, 'another-condition'], }); } // The hook can also skips default resolution and provide a custom URL. if (specifier === 'special-module') { return { url: 'file:///path/to/special-module.mjs', format: 'module', shortCircuit: true, // This is mandatory if not calling nextResolve(). }; } // If no customization is needed, defer to the next hook in the chain which would be the // Node.js default resolve if this is the last user-specified loader. return nextResolve(specifier); } ``` #### Asynchronous `load(url, context, nextLoad)` \* `url` {string} The URL returned by the `resolve` chain \* `context` {Object} \* `conditions` {string\[]} Export conditions of the relevant `package.json` \* `format` {string|null|undefined} The format optionally supplied by the `resolve` hook chain. This can be any string value as an input; input values do not need to | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.0601402148604393,
-0.01907774992287159,
0.0012408255133777857,
0.01884475350379944,
-0.008462621830403805,
-0.06767478585243225,
0.023422017693519592,
0.02542698010802269,
0.009174085222184658,
-0.038166847079992294,
-0.012567855417728424,
0.011253404431045055,
-0.03582366555929184,
-0.... | 0.108101 |
nextLoad)` \* `url` {string} The URL returned by the `resolve` chain \* `context` {Object} \* `conditions` {string\[]} Export conditions of the relevant `package.json` \* `format` {string|null|undefined} The format optionally supplied by the `resolve` hook chain. This can be any string value as an input; input values do not need to conform to the list of acceptable return values described below. \* `importAttributes` {Object} \* `nextLoad` {Function} The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook \* `url` {string} \* `context` {Object|undefined} When omitted, defaults are provided. When provided, defaults are merged in with preference to the provided properties. In the default `nextLoad`, if the module pointed to by `url` does not have explicit module type information, `context.format` is mandatory. \* Returns: {Promise} The asynchronous version takes either an object containing the following properties, or a `Promise` that will resolve to such an object. \* `format` {string} \* `shortCircuit` {undefined|boolean} A signal that this hook intends to terminate the chain of `load` hooks. \*\*Default:\*\* `false` \* `source` {string|ArrayBuffer|TypedArray} The source for Node.js to evaluate > \*\*Warning\*\*: The asynchronous `load` hook and namespaced exports from CommonJS > modules are incompatible. Attempting to use them together will result in an empty > object from the import. This may be addressed in the future. This does not apply > to the synchronous `load` hook, in which case exports can be used as usual. The asynchronous version works similarly to the synchronous version, though when using the asynchronous `load` hook, omitting vs providing a `source` for `'commonjs'` has very different effects: \* When a `source` is provided, all `require` calls from this module will be processed by the ESM loader with registered `resolve` and `load` hooks; all `require.resolve` calls from this module will be processed by the ESM loader with registered `resolve` hooks; only a subset of the CommonJS API will be available (e.g. no `require.extensions`, no `require.cache`, no `require.resolve.paths`) and monkey-patching on the CommonJS module loader will not apply. \* If `source` is undefined or `null`, it will be handled by the CommonJS module loader and `require`/`require.resolve` calls will not go through the registered hooks. This behavior for nullish `source` is temporary — in the future, nullish `source` will not be supported. These caveats do not apply to the synchronous `load` hook, in which case the complete set of CommonJS APIs available to the customized CommonJS modules, and `require`/`require.resolve` always go through the registered hooks. The Node.js internal asynchronous `load` implementation, which is the value of `next` for the last hook in the `load` chain, returns `null` for `source` when `format` is `'commonjs'` for backward compatibility. Here is an example hook that would opt-in to using the non-default behavior: ```mjs import { readFile } from 'node:fs/promises'; // Asynchronous version accepted by module.register(). This fix is not needed // for the synchronous version accepted by module.registerHooks(). export async function load(url, context, nextLoad) { const result = await nextLoad(url, context); if (result.format === 'commonjs') { result.source ??= await readFile(new URL(result.responseURL ?? url)); } return result; } ``` This doesn't apply to the synchronous `load` hook either, in which case the `source` returned contains source code loaded by the next hook, regardless of module format. ### Examples The various module customization hooks can be used together to accomplish wide-ranging customizations of the Node.js code loading and evaluation behaviors. #### Import from HTTPS The hook below registers hooks to enable rudimentary support for such specifiers. While this may seem like a significant improvement to Node.js core functionality, there are substantial downsides to actually using these hooks: performance is | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.09088847041130066,
0.05898592248558998,
0.01847219094634056,
0.05534641817212105,
-0.02243741787970066,
0.005144509486854076,
-0.026149136945605278,
0.016502637416124344,
0.024559134617447853,
-0.0400376133620739,
-0.02595309354364872,
0.024645937606692314,
-0.016751166433095932,
0.0209... | 0.058069 |
accomplish wide-ranging customizations of the Node.js code loading and evaluation behaviors. #### Import from HTTPS The hook below registers hooks to enable rudimentary support for such specifiers. While this may seem like a significant improvement to Node.js core functionality, there are substantial downsides to actually using these hooks: performance is much slower than loading files from disk, there is no caching, and there is no security. ```mjs // https-hooks.mjs import { get } from 'node:https'; export function load(url, context, nextLoad) { // For JavaScript to be loaded over the network, we need to fetch and // return it. if (url.startsWith('https://')) { return new Promise((resolve, reject) => { get(url, (res) => { let data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => data += chunk); res.on('end', () => resolve({ // This example assumes all network-provided JavaScript is ES module // code. format: 'module', shortCircuit: true, source: data, })); }).on('error', (err) => reject(err)); }); } // Let Node.js handle all other URLs. return nextLoad(url); } ``` ```mjs // main.mjs import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js'; console.log(VERSION); ``` With the preceding hooks module, running `node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs` prints the current version of CoffeeScript per the module at the URL in `main.mjs`. #### Transpilation Sources that are in formats Node.js doesn't understand can be converted into JavaScript using the [`load` hook][load hook]. This is less performant than transpiling source files before running Node.js; transpiler hooks should only be used for development and testing purposes. ##### Asynchronous version ```mjs // coffeescript-hooks.mjs import { readFile } from 'node:fs/promises'; import { findPackageJSON } from 'node:module'; import coffeescript from 'coffeescript'; const extensionsRegex = /\.(coffee|litcoffee|coffee\.md)$/; export async function load(url, context, nextLoad) { if (extensionsRegex.test(url)) { // CoffeeScript files can be either CommonJS or ES modules. Use a custom format // to tell Node.js not to detect its module type. const { source: rawSource } = await nextLoad(url, { ...context, format: 'coffee' }); // This hook converts CoffeeScript source code into JavaScript source code // for all imported CoffeeScript files. const transformedSource = coffeescript.compile(rawSource.toString(), url); // To determine how Node.js would interpret the transpilation result, // search up the file system for the nearest parent package.json file // and read its "type" field. return { format: await getPackageType(url), shortCircuit: true, source: transformedSource, }; } // Let Node.js handle all other URLs. return nextLoad(url, context); } async function getPackageType(url) { // `url` is only a file path during the first iteration when passed the // resolved url from the load() hook // an actual file path from load() will contain a file extension as it's // required by the spec // this simple truthy check for whether `url` contains a file extension will // work for most projects but does not cover some edge-cases (such as // extensionless files or a url ending in a trailing space) const pJson = findPackageJSON(url); return readFile(pJson, 'utf8') .then(JSON.parse) .then((json) => json?.type) .catch(() => undefined); } ``` ##### Synchronous version ```mjs // coffeescript-sync-hooks.mjs import { readFileSync } from 'node:fs'; import { registerHooks, findPackageJSON } from 'node:module'; import coffeescript from 'coffeescript'; const extensionsRegex = /\.(coffee|litcoffee|coffee\.md)$/; function load(url, context, nextLoad) { if (extensionsRegex.test(url)) { const { source: rawSource } = nextLoad(url, { ...context, format: 'coffee' }); const transformedSource = coffeescript.compile(rawSource.toString(), url); return { format: getPackageType(url), shortCircuit: true, source: transformedSource, }; } return nextLoad(url, context); } function getPackageType(url) { const pJson = findPackageJSON(url); if (!pJson) { return undefined; } try { const file = readFileSync(pJson, 'utf-8'); return JSON.parse(file)?.type; } catch { return undefined; } } registerHooks({ load }); ``` #### Running hooks ```coffee # main.coffee import { | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.07551990449428558,
0.05779383331537247,
0.06285544484853745,
0.06021177023649216,
0.024902446195483208,
-0.04884220287203789,
-0.11313633620738983,
0.037497904151678085,
0.05342250317335129,
0.027377616614103317,
-0.09158167988061905,
0.06170342117547989,
-0.024566059932112694,
-0.03150... | 0.024744 |
true, source: transformedSource, }; } return nextLoad(url, context); } function getPackageType(url) { const pJson = findPackageJSON(url); if (!pJson) { return undefined; } try { const file = readFileSync(pJson, 'utf-8'); return JSON.parse(file)?.type; } catch { return undefined; } } registerHooks({ load }); ``` #### Running hooks ```coffee # main.coffee import { scream } from './scream.coffee' console.log scream 'hello, world' import { version } from 'node:process' console.log "Brought to you by Node.js version #{version}" ``` ```coffee # scream.coffee export scream = (str) -> str.toUpperCase() ``` For the sake of running the example, add a `package.json` file containing the module type of the CoffeeScript files. ```json { "type": "module" } ``` This is only for running the example. In real world loaders, `getPackageType()` must be able to return an `format` known to Node.js even in the absence of an explicit type in a `package.json`, or otherwise the `nextLoad` call would throw `ERR\_UNKNOWN\_FILE\_EXTENSION` (if undefined) or `ERR\_UNKNOWN\_MODULE\_FORMAT` (if it's not a known format listed in the [load hook][] documentation). With the preceding hooks modules, running `node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee` or `node --import ./coffeescript-sync-hooks.mjs ./main.coffee` causes `main.coffee` to be turned into JavaScript after its source code is loaded from disk but before Node.js executes it; and so on for any `.coffee`, `.litcoffee` or `.coffee.md` files referenced via `import` statements of any loaded file. #### Import maps The previous two examples defined `load` hooks. This is an example of a `resolve` hook. This hooks module reads an `import-map.json` file that defines which specifiers to override to other URLs (this is a very simplistic implementation of a small subset of the "import maps" specification). ##### Asynchronous version ```mjs // import-map-hooks.js import fs from 'node:fs/promises'; const { imports } = JSON.parse(await fs.readFile('import-map.json')); export async function resolve(specifier, context, nextResolve) { if (Object.hasOwn(imports, specifier)) { return nextResolve(imports[specifier], context); } return nextResolve(specifier, context); } ``` ##### Synchronous version ```mjs // import-map-sync-hooks.js import fs from 'node:fs/promises'; import module from 'node:module'; const { imports } = JSON.parse(fs.readFileSync('import-map.json', 'utf-8')); function resolve(specifier, context, nextResolve) { if (Object.hasOwn(imports, specifier)) { return nextResolve(imports[specifier], context); } return nextResolve(specifier, context); } module.registerHooks({ resolve }); ``` ##### Using the hooks With these files: ```mjs // main.js import 'a-module'; ``` ```json // import-map.json { "imports": { "a-module": "./some-module.js" } } ``` ```mjs // some-module.js console.log('some module!'); ``` Running `node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js` or `node --import ./import-map-sync-hooks.js main.js` should print `some module!`. ## Source Map Support > Stability: 1 - Experimental Node.js supports TC39 ECMA-426 [Source Map][] format (it was called Source map revision 3 format). The APIs in this section are helpers for interacting with the source map cache. This cache is populated when source map parsing is enabled and [source map include directives][] are found in a modules' footer. To enable source map parsing, Node.js must be run with the flag [`--enable-source-maps`][], or with code coverage enabled by setting [`NODE\_V8\_COVERAGE=dir`][], or be enabled programmatically via [`module.setSourceMapsSupport()`][]. ```mjs // module.mjs // In an ECMAScript module import { findSourceMap, SourceMap } from 'node:module'; ``` ```cjs // module.cjs // In a CommonJS module const { findSourceMap, SourceMap } = require('node:module'); ``` ### `module.getSourceMapsSupport()` \* Returns: {Object} \* `enabled` {boolean} If the source maps support is enabled \* `nodeModules` {boolean} If the support is enabled for files in `node\_modules`. \* `generatedCode` {boolean} If the support is enabled for generated code from `eval` or `new Function`. This method returns whether the [Source Map v3][Source Map] support for stack traces is enabled. ### `module.findSourceMap(path)` \* `path` {string} \* Returns: {module.SourceMap|undefined} Returns `module.SourceMap` | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.1005992442369461,
-0.0034943216014653444,
0.0036746023688465357,
0.03505708649754524,
0.04003645107150078,
0.0003923655895050615,
0.016283225268125534,
0.06587112694978714,
0.032166533172130585,
-0.10640881955623627,
-0.012971725314855576,
0.011856436729431152,
-0.06962913274765015,
0.0... | 0.023078 |
If the support is enabled for files in `node\_modules`. \* `generatedCode` {boolean} If the support is enabled for generated code from `eval` or `new Function`. This method returns whether the [Source Map v3][Source Map] support for stack traces is enabled. ### `module.findSourceMap(path)` \* `path` {string} \* Returns: {module.SourceMap|undefined} Returns `module.SourceMap` if a source map is found, `undefined` otherwise. `path` is the resolved path for the file for which a corresponding source map should be fetched. ### `module.setSourceMapsSupport(enabled[, options])` \* `enabled` {boolean} Enable the source map support. \* `options` {Object} Optional \* `nodeModules` {boolean} If enabling the support for files in `node\_modules`. \*\*Default:\*\* `false`. \* `generatedCode` {boolean} If enabling the support for generated code from `eval` or `new Function`. \*\*Default:\*\* `false`. This function enables or disables the [Source Map v3][Source Map] support for stack traces. It provides same features as launching Node.js process with commandline options `--enable-source-maps`, with additional options to alter the support for files in `node\_modules` or generated codes. Only source maps in JavaScript files that are loaded after source maps has been enabled will be parsed and loaded. Preferably, use the commandline options `--enable-source-maps` to avoid losing track of source maps of modules loaded before this API call. ### Class: `module.SourceMap` #### `new SourceMap(payload[, { lineLengths }])` \* `payload` {Object} \* `lineLengths` {number\[]} Creates a new `sourceMap` instance. `payload` is an object with keys matching the [Source map format][]: \* `file` {string} \* `version` {number} \* `sources` {string\[]} \* `sourcesContent` {string\[]} \* `names` {string\[]} \* `mappings` {string} \* `sourceRoot` {string} `lineLengths` is an optional array of the length of each line in the generated code. #### `sourceMap.payload` \* Returns: {Object} Getter for the payload used to construct the [`SourceMap`][] instance. #### `sourceMap.findEntry(lineOffset, columnOffset)` \* `lineOffset` {number} The zero-indexed line number offset in the generated source \* `columnOffset` {number} The zero-indexed column number offset in the generated source \* Returns: {Object} Given a line offset and column offset in the generated source file, returns an object representing the SourceMap range in the original file if found, or an empty object if not. The object returned contains the following keys: \* `generatedLine` {number} The line offset of the start of the range in the generated source \* `generatedColumn` {number} The column offset of start of the range in the generated source \* `originalSource` {string} The file name of the original source, as reported in the SourceMap \* `originalLine` {number} The line offset of the start of the range in the original source \* `originalColumn` {number} The column offset of start of the range in the original source \* `name` {string} The returned value represents the raw range as it appears in the SourceMap, based on zero-indexed offsets, \_not\_ 1-indexed line and column numbers as they appear in Error messages and CallSite objects. To get the corresponding 1-indexed line and column numbers from a lineNumber and columnNumber as they are reported by Error stacks and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` #### `sourceMap.findOrigin(lineNumber, columnNumber)` \* `lineNumber` {number} The 1-indexed line number of the call site in the generated source \* `columnNumber` {number} The 1-indexed column number of the call site in the generated source \* Returns: {Object} Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, find the corresponding call site location in the original source. If the `lineNumber` and `columnNumber` provided are not found in any source map, then an empty object is returned. Otherwise, the returned object contains the following keys: \* `name` {string|undefined} The name of the range in the source map, if one was provided \* `fileName` {string} The file name of the | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.03235114365816116,
-0.0051540895365178585,
-0.025572171434760094,
0.06196877360343933,
0.12073881179094315,
0.005691823549568653,
-0.03629130497574806,
0.00291833677329123,
-0.07814981788396835,
-0.009743702597916126,
0.07553575187921524,
-0.013691620901226997,
-0.030359728261828423,
-0... | 0.018336 |
the `lineNumber` and `columnNumber` provided are not found in any source map, then an empty object is returned. Otherwise, the returned object contains the following keys: \* `name` {string|undefined} The name of the range in the source map, if one was provided \* `fileName` {string} The file name of the original source, as reported in the SourceMap \* `lineNumber` {number} The 1-indexed lineNumber of the corresponding call site in the original source \* `columnNumber` {number} The 1-indexed columnNumber of the corresponding call site in the original source [CommonJS]: modules.md [Conditional exports]: packages.md#conditional-exports [Customization hooks]: #customization-hooks [ES Modules]: esm.md [Permission Model]: permissions.md#permission-model [Source Map]: https://tc39.es/ecma426/ [Source map format]: https://tc39.es/ecma426/#sec-source-map-format [V8 JavaScript code coverage]: https://v8project.blogspot.com/2017/12/javascript-code-coverage.html [V8 code cache]: https://v8.dev/blog/code-caching-for-devs [`"exports"`]: packages.md#exports [`--enable-source-maps`]: cli.md#--enable-source-maps [`--import`]: cli.md#--importmodule [`--require`]: cli.md#-r---require-module [`NODE\_COMPILE\_CACHE=dir`]: cli.md#node\_compile\_cachedir [`NODE\_COMPILE\_CACHE\_PORTABLE=1`]: cli.md#node\_compile\_cache\_portable1 [`NODE\_DISABLE\_COMPILE\_CACHE=1`]: cli.md#node\_disable\_compile\_cache1 [`NODE\_V8\_COVERAGE=dir`]: cli.md#node\_v8\_coveragedir [`SourceMap`]: #class-modulesourcemap [`initialize`]: #initialize [`module.constants.compileCacheStatus`]: #moduleconstantscompilecachestatus [`module.enableCompileCache()`]: #moduleenablecompilecacheoptions [`module.flushCompileCache()`]: #moduleflushcompilecache [`module.getCompileCacheDir()`]: #modulegetcompilecachedir [`module.registerHooks()`]: #moduleregisterhooksoptions [`module.setSourceMapsSupport()`]: #modulesetsourcemapssupportenabled-options [`module`]: #the-module-object [`os.tmpdir()`]: os.md#ostmpdir [`register`]: #moduleregisterspecifier-parenturl-options [`util.TextDecoder`]: util.md#class-utiltextdecoder [accepted final formats]: #accepted-final-formats-returned-by-load [asynchronous `load` hook]: #asynchronous-loadurl-context-nextload [asynchronous `resolve` hook]: #asynchronous-resolvespecifier-context-nextresolve [asynchronous hook functions]: #asynchronous-hooks-accepted-by-moduleregister [caveats of asynchronous customization hooks]: #caveats-of-asynchronous-customization-hooks [hooks]: #customization-hooks [load hook]: #synchronous-loadurl-context-nextload [module compile cache]: #module-compile-cache [module wrapper]: modules.md#the-module-wrapper [realm]: https://tc39.es/ecma262/#realm [resolve hook]: #synchronous-resolvespecifier-context-nextresolve [source map include directives]: https://tc39.es/ecma426/#sec-linking-generated-code [synchronous hook functions]: #hook-functions-accepted-by-moduleregisterhooks [the documentation of `Worker`]: worker\_threads.md#new-workerfilename-options [transferable objects]: worker\_threads.md#portpostmessagevalue-transferlist [transform TypeScript features]: typescript.md#typescript-features [type-stripping]: typescript.md#type-stripping | https://github.com/nodejs/node/blob/main//doc/api/module.md | main | nodejs | [
-0.03721105307340622,
0.053108733147382736,
-0.03263889253139496,
-0.0064443498849868774,
0.13562661409378052,
-0.01744568720459938,
0.019422031939029694,
0.026528656482696533,
0.020649565383791924,
0.03212974965572357,
0.011384008452296257,
-0.07673153281211853,
-0.057954464107751846,
-0.... | 0.062775 |
# Errors Applications running in Node.js will generally experience the following categories of errors: \* Standard JavaScript errors such as {EvalError}, {SyntaxError}, {RangeError}, {ReferenceError}, {TypeError}, and {URIError}. \* Standard `DOMException`s. \* System errors triggered by underlying operating system constraints such as attempting to open a file that does not exist or attempting to send data over a closed socket. \* `AssertionError`s are a special class of error that can be triggered when Node.js detects an exceptional logic violation that should never occur. These are raised typically by the `node:assert` module. \* User-specified errors triggered by application code. All JavaScript and system errors raised by Node.js inherit from, or are instances of, the standard JavaScript {Error} class and are guaranteed to provide \_at least\_ the properties available on that class. The [`error.message`][] property of errors raised by Node.js may be changed in any versions. Use [`error.code`][] to identify an error instead. For a `DOMException`, use [`domException.name`][] to identify its type. ## Error propagation and interception Node.js supports several mechanisms for propagating and handling errors that occur while an application is running. How these errors are reported and handled depends entirely on the type of `Error` and the style of the API that is called. All JavaScript errors are handled as exceptions that \_immediately\_ generate and throw an error using the standard JavaScript `throw` mechanism. These are handled using the [`try…catch` construct][try-catch] provided by the JavaScript language. ```js // Throws with a ReferenceError because z is not defined. try { const m = 1; const n = m + z; } catch (err) { // Handle the error here. } ``` Any use of the JavaScript `throw` mechanism will raise an exception that \_must\_ be handled or the Node.js process will exit immediately. With few exceptions, \_Synchronous\_ APIs (any blocking method that does not return a {Promise} nor accept a `callback` function, such as [`fs.readFileSync`][]), will use `throw` to report errors. Errors that occur within \_Asynchronous APIs\_ may be reported in multiple ways: \* Some asynchronous methods returns a {Promise}, you should always take into account that it might be rejected. See [`--unhandled-rejections`][] flag for how the process will react to an unhandled promise rejection. ```js const fs = require('node:fs/promises'); (async () => { let data; try { data = await fs.readFile('a file that does not exist'); } catch (err) { console.error('There was an error reading the file!', err); return; } // Otherwise handle the data })(); ``` \* Most asynchronous methods that accept a `callback` function will accept an `Error` object passed as the first argument to that function. If that first argument is not `null` and is an instance of `Error`, then an error occurred that should be handled. ```js const fs = require('node:fs'); fs.readFile('a file that does not exist', (err, data) => { if (err) { console.error('There was an error reading the file!', err); return; } // Otherwise handle the data }); ``` \* When an asynchronous method is called on an object that is an [`EventEmitter`][], errors can be routed to that object's `'error'` event. ```js const net = require('node:net'); const connection = net.connect('localhost'); // Adding an 'error' event handler to a stream: connection.on('error', (err) => { // If the connection is reset by the server, or if it can't // connect at all, or on any sort of error encountered by // the connection, the error will be sent here. console.error(err); }); connection.pipe(process.stdout); ``` \* A handful of typically asynchronous methods in the Node.js API may still use the `throw` mechanism to raise exceptions that must be handled using `try…catch`. There is no comprehensive list of such | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.062240272760391235,
0.027866180986166,
0.06844081729650497,
0.0728336051106453,
0.09863225370645523,
-0.06461440771818161,
-0.012466990388929844,
0.04624300077557564,
0.04126453027129173,
0.020869484171271324,
-0.04785948619246483,
0.05119163915514946,
0.06125248596072197,
-0.0235360264... | 0.126919 |
of error encountered by // the connection, the error will be sent here. console.error(err); }); connection.pipe(process.stdout); ``` \* A handful of typically asynchronous methods in the Node.js API may still use the `throw` mechanism to raise exceptions that must be handled using `try…catch`. There is no comprehensive list of such methods; please refer to the documentation of each method to determine the appropriate error handling mechanism required. The use of the `'error'` event mechanism is most common for [stream-based][] and [event emitter-based][] APIs, which themselves represent a series of asynchronous operations over time (as opposed to a single operation that may pass or fail). For \_all\_ [`EventEmitter`][] objects, if an `'error'` event handler is not provided, the error will be thrown, causing the Node.js process to report an uncaught exception and crash unless either: a handler has been registered for the [`'uncaughtException'`][] event, or the deprecated [`node:domain`][domains] module is used. ```js const EventEmitter = require('node:events'); const ee = new EventEmitter(); setImmediate(() => { // This will crash the process because no 'error' event // handler has been added. ee.emit('error', new Error('This will crash')); }); ``` Errors generated in this way \_cannot\_ be intercepted using `try…catch` as they are thrown \_after\_ the calling code has already exited. Developers must refer to the documentation for each method to determine exactly how errors raised by those methods are propagated. ## Class: `Error` A generic JavaScript {Error} object that does not denote any specific circumstance of why the error occurred. `Error` objects capture a "stack trace" detailing the point in the code at which the `Error` was instantiated, and may provide a text description of the error. All errors generated by Node.js, including all system and JavaScript errors, will either be instances of, or inherit from, the `Error` class. ### `new Error(message[, options])` \* `message` {string} \* `options` {Object} \* `cause` {any} The error that caused the newly created error. Creates a new `Error` object and sets the `error.message` property to the provided text message. If an object is passed as `message`, the text message is generated by calling `String(message)`. If the `cause` option is provided, it is assigned to the `error.cause` property. The `error.stack` property will represent the point in the code at which `new Error()` was called. Stack traces are dependent on [V8's stack trace API][]. Stack traces extend only to either (a) the beginning of \_synchronous code execution\_, or (b) the number of frames given by the property `Error.stackTraceLimit`, whichever is smaller. ### `Error.captureStackTrace(targetObject[, constructorOpt])` \* `targetObject` {Object} \* `constructorOpt` {Function} Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ### `Error.stackTraceLimit` \* Type: {number} The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
0.013868861831724644,
0.02359529584646225,
0.02841118350625038,
0.04951511695981026,
0.05448136851191521,
-0.015219088643789291,
-0.028526542708277702,
0.075242780148983,
0.054756369441747665,
0.010190844535827637,
-0.08372510224580765,
0.004300975706428289,
-0.031394604593515396,
-0.03355... | 0.11877 |
Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ### `Error.stackTraceLimit` \* Type: {number} The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured \_after\_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ### `error.cause` \* Type: {any} If present, the `error.cause` property is the underlying cause of the `Error`. It is used when catching an error and throwing a new one with a different message or code in order to still have access to the original error. The `error.cause` property is typically set by calling `new Error(message, { cause })`. It is not set by the constructor if the `cause` option is not provided. This property allows errors to be chained. When serializing `Error` objects, [`util.inspect()`][] recursively serializes `error.cause` if it is set. ```js const cause = new Error('The remote HTTP server responded with a 500 status'); const symptom = new Error('The message failed to send', { cause }); console.log(symptom); // Prints: // Error: The message failed to send // at REPL2:1:17 // at Script.runInThisContext (node:vm:130:12) // ... 7 lines matching cause stack trace ... // at [\_line] [as \_line] (node:internal/readline/interface:886:18) { // [cause]: Error: The remote HTTP server responded with a 500 status // at REPL1:1:15 // at Script.runInThisContext (node:vm:130:12) // at REPLServer.defaultEval (node:repl:574:29) // at bound (node:domain:426:15) // at REPLServer.runBound [as eval] (node:domain:437:12) // at REPLServer.onLine (node:repl:902:10) // at REPLServer.emit (node:events:549:35) // at REPLServer.emit (node:domain:482:12) // at [\_onLine] [as \_onLine] (node:internal/readline/interface:425:12) // at [\_line] [as \_line] (node:internal/readline/interface:886:18) ``` ### `error.code` \* Type: {string} The `error.code` property is a string label that identifies the kind of error. `error.code` is the most stable way to identify an error. It will only change between major versions of Node.js. In contrast, `error.message` strings may change between any versions of Node.js. See [Node.js error codes][] for details about specific codes. ### `error.message` \* Type: {string} The `error.message` property is the string description of the error as set by calling `new Error(message)`. The `message` passed to the constructor will also appear in the first line of the stack trace of the `Error`, however changing this property after the `Error` object is created \_may not\_ change the first line of the stack trace (for example, when `error.stack` is read before this property is changed). ```js const err = new Error('The message'); console.error(err.message); // Prints: The message ``` ### `error.stack` \* Type: {string} The `error.stack` property is a string describing the point in the code at which the `Error` was instantiated. ```console Error: Things keep happening! at /home/gbusey/file.js:525:2 at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21) at Actor. (/home/gbusey/actors.js:400:8) at increaseSynergy (/home/gbusey/actors.js:701:6) ``` The first line is formatted as `: `, and is followed by a series of stack frames (each line beginning with "at "). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses. Frames are only generated for JavaScript functions. | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.03872191905975342,
-0.05922430381178856,
-0.008602508343756199,
0.021820390596985817,
0.025894371792674065,
-0.0223535168915987,
0.013964652083814144,
0.08591453731060028,
0.05758989229798317,
-0.045849207788705826,
-0.01605682075023651,
-0.04489414766430855,
-0.004165926482528448,
-0.0... | 0.100577 |
occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses. Frames are only generated for JavaScript functions. If, for example, execution synchronously passes through a C++ addon function called `cheetahify` which itself calls a JavaScript function, the frame representing the `cheetahify` call will not be present in the stack traces: ```js const cheetahify = require('./native-binding.node'); function makeFaster() { // `cheetahify()` \*synchronously\* calls speedy. cheetahify(function speedy() { throw new Error('oh no!'); }); } makeFaster(); // will throw: // /home/gbusey/file.js:6 // throw new Error('oh no!'); // ^ // Error: oh no! // at speedy (/home/gbusey/file.js:6:11) // at makeFaster (/home/gbusey/file.js:5:3) // at Object. (/home/gbusey/file.js:10:1) // at Module.\_compile (module.js:456:26) // at Object.Module.\_extensions..js (module.js:474:10) // at Module.load (module.js:356:32) // at Function.Module.\_load (module.js:312:12) // at Function.Module.runMain (module.js:497:10) // at startup (node.js:119:16) // at node.js:906:3 ``` The location information will be one of: \* `native`, if the frame represents a call internal to V8 (as in `[].forEach`). \* `plain-filename.js:line:column`, if the frame represents a call internal to Node.js. \* `/absolute/path/to/file.js:line:column`, if the frame represents a call in a user program (using CommonJS module system), or its dependencies. \* `:///url/to/module/file.mjs:line:column`, if the frame represents a call in a user program (using ES module system), or its dependencies. The number of frames captured by the stack trace is bounded by the smaller of `Error.stackTraceLimit` or the number of available frames on the current event loop tick. `error.stack` is a getter/setter for a hidden internal property which is only present on builtin `Error` objects (those for which [`Error.isError`][] returns true). If `error` is not a builtin error object, then the `error.stack` getter will always return `undefined`, and the setter will do nothing. This can occur if the accessor is manually invoked with a `this` value that is not a builtin error object, such as a {Proxy}. ## Class: `AssertionError` \* Extends: {errors.Error} Indicates the failure of an assertion. For details, see [`Class: assert.AssertionError`][]. ## Class: `RangeError` \* Extends: {errors.Error} Indicates that a provided argument was not within the set or range of acceptable values for a function; whether that is a numeric range, or outside the set of options for a given function parameter. ```js require('node:net').connect(-1); // Throws "RangeError: "port" option should be >= 0 and < 65536: -1" ``` Node.js will generate and throw `RangeError` instances \_immediately\_ as a form of argument validation. ## Class: `ReferenceError` \* Extends: {errors.Error} Indicates that an attempt is being made to access a variable that is not defined. Such errors commonly indicate typos in code, or an otherwise broken program. While client code may generate and propagate these errors, in practice, only V8 will do so. ```js doesNotExist; // Throws ReferenceError, doesNotExist is not a variable in this program. ``` Unless an application is dynamically generating and running code, `ReferenceError` instances indicate a bug in the code or its dependencies. ## Class: `SyntaxError` \* Extends: {errors.Error} Indicates that a program is not valid JavaScript. These errors may only be generated and propagated as a result of code evaluation. Code evaluation may happen as a result of `eval`, `Function`, `require`, or [vm][]. These errors are almost always indicative of a broken program. ```js try { require('node:vm').runInThisContext('binary ! isNotOk'); } catch (err) { // 'err' will be a SyntaxError. } ``` `SyntaxError` instances are unrecoverable in the context that created them – they may only be caught by other contexts. ## Class: `SystemError` \* Extends: {errors.Error} Node.js generates system errors when exceptions | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.07417674362659454,
-0.028880858793854713,
0.0074216690845787525,
0.0248465184122324,
0.03207665681838989,
-0.06286196410655975,
-0.022847436368465424,
-0.003805391024798155,
0.08518581092357635,
-0.13090798258781433,
0.03821457177400589,
0.022982530295848846,
-0.09431666880846024,
-0.06... | 0.090949 |
program. ```js try { require('node:vm').runInThisContext('binary ! isNotOk'); } catch (err) { // 'err' will be a SyntaxError. } ``` `SyntaxError` instances are unrecoverable in the context that created them – they may only be caught by other contexts. ## Class: `SystemError` \* Extends: {errors.Error} Node.js generates system errors when exceptions occur within its runtime environment. These usually occur when an application violates an operating system constraint. For example, a system error will occur if an application attempts to read a file that does not exist. \* `address` {string} If present, the address to which a network connection failed \* `code` {string} The string error code \* `dest` {string} If present, the file path destination when reporting a file system error \* `errno` {number} The system-provided error number \* `info` {Object} If present, extra details about the error condition \* `message` {string} A system-provided human-readable description of the error \* `path` {string} If present, the file path when reporting a file system error \* `port` {number} If present, the network connection port that is not available \* `syscall` {string} The name of the system call that triggered the error ### `error.address` \* Type: {string} If present, `error.address` is a string describing the address to which a network connection failed. ### `error.code` \* Type: {string} The `error.code` property is a string representing the error code. ### `error.dest` \* Type: {string} If present, `error.dest` is the file path destination when reporting a file system error. ### `error.errno` \* Type: {number} The `error.errno` property is a negative number which corresponds to the error code defined in [`libuv Error handling`][]. On Windows the error number provided by the system will be normalized by libuv. To get the string representation of the error code, use [`util.getSystemErrorName(error.errno)`][]. ### `error.info` \* Type: {Object} If present, `error.info` is an object with details about the error condition. ### `error.message` \* Type: {string} `error.message` is a system-provided human-readable description of the error. ### `error.path` \* Type: {string} If present, `error.path` is a string containing a relevant invalid pathname. ### `error.port` \* Type: {number} If present, `error.port` is the network connection port that is not available. ### `error.syscall` \* Type: {string} The `error.syscall` property is a string describing the [syscall][] that failed. ### Common system errors This is a list of system errors commonly-encountered when writing a Node.js program. For a comprehensive list, see the [`errno`(3) man page][]. \* `EACCES` (Permission denied): An attempt was made to access a file in a way forbidden by its file access permissions. \* `EADDRINUSE` (Address already in use): An attempt to bind a server ([`net`][], [`http`][], or [`https`][]) to a local address failed due to another server on the local system already occupying that address. \* `ECONNREFUSED` (Connection refused): No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host. \* `ECONNRESET` (Connection reset by peer): A connection was forcibly closed by a peer. This normally results from a loss of the connection on the remote socket due to a timeout or reboot. Commonly encountered via the [`http`][] and [`net`][] modules. \* `EEXIST` (File exists): An existing file was the target of an operation that required that the target not exist. \* `EISDIR` (Is a directory): An operation expected a file, but the given pathname was a directory. \* `EMFILE` (Too many open files in system): Maximum number of [file descriptors][] allowable on the system has been reached, and requests for another descriptor cannot be fulfilled until at least one has been closed. This is encountered when | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.04694998264312744,
0.03325439617037773,
0.0050604999996721745,
0.030107714235782623,
0.09047097712755203,
-0.05614336207509041,
-0.0011030883761122823,
0.10608445107936859,
0.011791262775659561,
0.013818138279020786,
-0.01088580209761858,
0.016272127628326416,
0.07433000952005386,
-0.05... | 0.172757 |
operation expected a file, but the given pathname was a directory. \* `EMFILE` (Too many open files in system): Maximum number of [file descriptors][] allowable on the system has been reached, and requests for another descriptor cannot be fulfilled until at least one has been closed. This is encountered when opening many files at once in parallel, especially on systems (in particular, macOS) where there is a low file descriptor limit for processes. To remedy a low limit, run `ulimit -n 2048` in the same shell that will run the Node.js process. \* `ENOENT` (No such file or directory): Commonly raised by [`fs`][] operations to indicate that a component of the specified pathname does not exist. No entity (file or directory) could be found by the given path. \* `ENOTDIR` (Not a directory): A component of the given pathname existed, but was not a directory as expected. Commonly raised by [`fs.readdir`][]. \* `ENOTEMPTY` (Directory not empty): A directory with entries was the target of an operation that requires an empty directory, usually [`fs.unlink`][]. \* `ENOTFOUND` (DNS lookup failed): Indicates a DNS failure of either `EAI\_NODATA` or `EAI\_NONAME`. This is not a standard POSIX error. \* `EPERM` (Operation not permitted): An attempt was made to perform an operation that requires elevated privileges. \* `EPIPE` (Broken pipe): A write on a pipe, socket, or FIFO for which there is no process to read the data. Commonly encountered at the [`net`][] and [`http`][] layers, indicative that the remote side of the stream being written to has been closed. \* `ETIMEDOUT` (Operation timed out): A connect or send request failed because the connected party did not properly respond after a period of time. Usually encountered by [`http`][] or [`net`][]. Often a sign that a `socket.end()` was not properly called. ## Class: `TypeError` \* Extends {errors.Error} Indicates that a provided argument is not an allowable type. For example, passing a function to a parameter which expects a string would be a `TypeError`. ```js require('node:url').parse(() => { }); // Throws TypeError, since it expected a string. ``` Node.js will generate and throw `TypeError` instances \_immediately\_ as a form of argument validation. ## Exceptions vs. errors A JavaScript exception is a value that is thrown as a result of an invalid operation or as the target of a `throw` statement. While it is not required that these values are instances of `Error` or classes which inherit from `Error`, all exceptions thrown by Node.js or the JavaScript runtime \_will\_ be instances of `Error`. Some exceptions are \_unrecoverable\_ at the JavaScript layer. Such exceptions will \_always\_ cause the Node.js process to crash. Examples include `assert()` checks or `abort()` calls in the C++ layer. ## OpenSSL errors Errors originating in `crypto` or `tls` are of class `Error`, and in addition to the standard `.code` and `.message` properties, may have some additional OpenSSL-specific properties. ### `error.opensslErrorStack` An array of errors that can give context to where in the OpenSSL library an error originates from. ### `error.function` The OpenSSL function the error originates in. ### `error.library` The OpenSSL library the error originates in. ### `error.reason` A human-readable string describing the reason for the error. ## Node.js error codes ### `ABORT\_ERR` Used when an operation has been aborted (typically using an `AbortController`). APIs \_not\_ using `AbortSignal`s typically do not raise an error with this code. This code does not use the regular `ERR\_\*` convention Node.js errors use in order to be compatible with the web platform's `AbortError`. ### `ERR\_ACCESS\_DENIED` A special type of error that is triggered whenever Node.js tries to get access to a resource restricted by the [Permission Model][]. ### `ERR\_AMBIGUOUS\_ARGUMENT` | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.045455675572156906,
-0.025309303775429726,
-0.021494638174772263,
-0.013178040273487568,
0.1046394631266594,
-0.10728993266820908,
-0.03569211810827255,
0.10907094925642014,
0.07354087382555008,
0.06412189453840256,
0.004177632741630077,
0.03204290196299553,
-0.005423711147159338,
-0.02... | 0.199073 |
this code. This code does not use the regular `ERR\_\*` convention Node.js errors use in order to be compatible with the web platform's `AbortError`. ### `ERR\_ACCESS\_DENIED` A special type of error that is triggered whenever Node.js tries to get access to a resource restricted by the [Permission Model][]. ### `ERR\_AMBIGUOUS\_ARGUMENT` A function argument is being used in a way that suggests that the function signature may be misunderstood. This is thrown by the `node:assert` module when the `message` parameter in `assert.throws(block, message)` matches the error message thrown by `block` because that usage suggests that the user believes `message` is the expected message rather than the message the `AssertionError` will display if `block` does not throw. ### `ERR\_ARG\_NOT\_ITERABLE` An iterable argument (i.e. a value that works with `for...of` loops) was required, but not provided to a Node.js API. ### `ERR\_ASSERTION` A special type of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically by the `node:assert` module. ### `ERR\_ASYNC\_CALLBACK` An attempt was made to register something that is not a function as an `AsyncHooks` callback. ### `ERR\_ASYNC\_LOADER\_REQUEST\_NEVER\_SETTLED` An operation related to module loading is customized by an asynchronous loader hook that never settled the promise before the loader thread exits. ### `ERR\_ASYNC\_TYPE` The type of an asynchronous resource was invalid. Users are also able to define their own types if using the public embedder API. ### `ERR\_BROTLI\_COMPRESSION\_FAILED` Data passed to a Brotli stream was not successfully compressed. ### `ERR\_BROTLI\_INVALID\_PARAM` An invalid parameter key was passed during construction of a Brotli stream. ### `ERR\_BUFFER\_CONTEXT\_NOT\_AVAILABLE` An attempt was made to create a Node.js `Buffer` instance from addon or embedder code, while in a JS engine Context that is not associated with a Node.js instance. The data passed to the `Buffer` method will have been released by the time the method returns. When encountering this error, a possible alternative to creating a `Buffer` instance is to create a normal `Uint8Array`, which only differs in the prototype of the resulting object. `Uint8Array`s are generally accepted in all Node.js core APIs where `Buffer`s are; they are available in all Contexts. ### `ERR\_BUFFER\_OUT\_OF\_BOUNDS` An operation outside the bounds of a `Buffer` was attempted. ### `ERR\_BUFFER\_TOO\_LARGE` An attempt has been made to create a `Buffer` larger than the maximum allowed size. ### `ERR\_CANNOT\_WATCH\_SIGINT` Node.js was unable to watch for the `SIGINT` signal. ### `ERR\_CHILD\_CLOSED\_BEFORE\_REPLY` A child process was closed before the parent received a reply. ### `ERR\_CHILD\_PROCESS\_IPC\_REQUIRED` Used when a child process is being forked without specifying an IPC channel. ### `ERR\_CHILD\_PROCESS\_STDIO\_MAXBUFFER` Used when the main process is trying to read data from the child process's STDERR/STDOUT, and the data's length is longer than the `maxBuffer` option. ### `ERR\_CLOSED\_MESSAGE\_PORT` There was an attempt to use a `MessagePort` instance in a closed state, usually after `.close()` has been called. ### `ERR\_CONSOLE\_WRITABLE\_STREAM` `Console` was instantiated without `stdout` stream, or `Console` has a non-writable `stdout` or `stderr` stream. ### `ERR\_CONSTRUCT\_CALL\_INVALID` A class constructor was called that is not callable. ### `ERR\_CONSTRUCT\_CALL\_REQUIRED` A constructor for a class was called without `new`. ### `ERR\_CONTEXT\_NOT\_INITIALIZED` The vm context passed into the API is not yet initialized. This could happen when an error occurs (and is caught) during the creation of the context, for example, when the allocation fails or the maximum call stack size is reached when the context is created. ### `ERR\_CPU\_PROFILE\_ALREADY\_STARTED` The CPU profile with the given name is already started. ### `ERR\_CPU\_PROFILE\_NOT\_STARTED` The CPU profile with the given name is not started. ### `ERR\_CPU\_PROFILE\_TOO\_MANY` There are too many CPU profiles being collected. ### `ERR\_CRYPTO\_ARGON2\_NOT\_SUPPORTED` Argon2 is not supported by the | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.080411896109581,
0.06647758930921555,
0.013404667377471924,
0.055416274815797806,
0.11287738382816315,
-0.09904157370328903,
0.053018637001514435,
0.014683492481708527,
0.010033268481492996,
-0.04591939225792885,
0.01268809661269188,
0.02381403185427189,
0.03846760466694832,
0.008971942... | 0.106196 |
size is reached when the context is created. ### `ERR\_CPU\_PROFILE\_ALREADY\_STARTED` The CPU profile with the given name is already started. ### `ERR\_CPU\_PROFILE\_NOT\_STARTED` The CPU profile with the given name is not started. ### `ERR\_CPU\_PROFILE\_TOO\_MANY` There are too many CPU profiles being collected. ### `ERR\_CRYPTO\_ARGON2\_NOT\_SUPPORTED` Argon2 is not supported by the current version of OpenSSL being used. ### `ERR\_CRYPTO\_CUSTOM\_ENGINE\_NOT\_SUPPORTED` An OpenSSL engine was requested (for example, through the `clientCertEngine` or `privateKeyEngine` TLS options) that is not supported by the version of OpenSSL being used, likely due to the compile-time flag `OPENSSL\_NO\_ENGINE`. ### `ERR\_CRYPTO\_ECDH\_INVALID\_FORMAT` An invalid value for the `format` argument was passed to the `crypto.ECDH()` class `getPublicKey()` method. ### `ERR\_CRYPTO\_ECDH\_INVALID\_PUBLIC\_KEY` An invalid value for the `key` argument has been passed to the `crypto.ECDH()` class `computeSecret()` method. It means that the public key lies outside of the elliptic curve. ### `ERR\_CRYPTO\_ENGINE\_UNKNOWN` An invalid crypto engine identifier was passed to [`require('node:crypto').setEngine()`][]. ### `ERR\_CRYPTO\_FIPS\_FORCED` The [`--force-fips`][] command-line argument was used but there was an attempt to enable or disable FIPS mode in the `node:crypto` module. ### `ERR\_CRYPTO\_FIPS\_UNAVAILABLE` An attempt was made to enable or disable FIPS mode, but FIPS mode was not available. ### `ERR\_CRYPTO\_HASH\_FINALIZED` [`hash.digest()`][] was called multiple times. The `hash.digest()` method must be called no more than one time per instance of a `Hash` object. ### `ERR\_CRYPTO\_HASH\_UPDATE\_FAILED` [`hash.update()`][] failed for any reason. This should rarely, if ever, happen. ### `ERR\_CRYPTO\_INCOMPATIBLE\_KEY` The given crypto keys are incompatible with the attempted operation. ### `ERR\_CRYPTO\_INCOMPATIBLE\_KEY\_OPTIONS` The selected public or private key encoding is incompatible with other options. ### `ERR\_CRYPTO\_INITIALIZATION\_FAILED` Initialization of the crypto subsystem failed. ### `ERR\_CRYPTO\_INVALID\_AUTH\_TAG` An invalid authentication tag was provided. ### `ERR\_CRYPTO\_INVALID\_COUNTER` An invalid counter was provided for a counter-mode cipher. ### `ERR\_CRYPTO\_INVALID\_CURVE` An invalid elliptic-curve was provided. ### `ERR\_CRYPTO\_INVALID\_DIGEST` An invalid [crypto digest algorithm][] was specified. ### `ERR\_CRYPTO\_INVALID\_IV` An invalid initialization vector was provided. ### `ERR\_CRYPTO\_INVALID\_JWK` An invalid JSON Web Key was provided. ### `ERR\_CRYPTO\_INVALID\_KEYLEN` An invalid key length was provided. ### `ERR\_CRYPTO\_INVALID\_KEYPAIR` An invalid key pair was provided. ### `ERR\_CRYPTO\_INVALID\_KEYTYPE` An invalid key type was provided. ### `ERR\_CRYPTO\_INVALID\_KEY\_OBJECT\_TYPE` The given crypto key object's type is invalid for the attempted operation. ### `ERR\_CRYPTO\_INVALID\_MESSAGELEN` An invalid message length was provided. ### `ERR\_CRYPTO\_INVALID\_SCRYPT\_PARAMS` One or more [`crypto.scrypt()`][] or [`crypto.scryptSync()`][] parameters are outside their legal range. ### `ERR\_CRYPTO\_INVALID\_STATE` A crypto method was used on an object that was in an invalid state. For instance, calling [`cipher.getAuthTag()`][] before calling `cipher.final()`. ### `ERR\_CRYPTO\_INVALID\_TAG\_LENGTH` An invalid authentication tag length was provided. ### `ERR\_CRYPTO\_JOB\_INIT\_FAILED` Initialization of an asynchronous crypto operation failed. ### `ERR\_CRYPTO\_JWK\_UNSUPPORTED\_CURVE` Key's Elliptic Curve is not registered for use in the [JSON Web Key Elliptic Curve Registry][]. ### `ERR\_CRYPTO\_JWK\_UNSUPPORTED\_KEY\_TYPE` Key's Asymmetric Key Type is not registered for use in the [JSON Web Key Types Registry][]. ### `ERR\_CRYPTO\_KEM\_NOT\_SUPPORTED` Attempted to use KEM operations while Node.js was not compiled with OpenSSL with KEM support. ### `ERR\_CRYPTO\_OPERATION\_FAILED` A crypto operation failed for an otherwise unspecified reason. ### `ERR\_CRYPTO\_PBKDF2\_ERROR` The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide more details and therefore neither does Node.js. ### `ERR\_CRYPTO\_SCRYPT\_NOT\_SUPPORTED` Node.js was compiled without `scrypt` support. Not possible with the official release binaries but can happen with custom builds, including distro builds. ### `ERR\_CRYPTO\_SIGN\_KEY\_REQUIRED` A signing `key` was not provided to the [`sign.sign()`][] method. ### `ERR\_CRYPTO\_TIMING\_SAFE\_EQUAL\_LENGTH` [`crypto.timingSafeEqual()`][] was called with `Buffer`, `TypedArray`, or `DataView` arguments of different lengths. ### `ERR\_CRYPTO\_UNKNOWN\_CIPHER` An unknown cipher was specified. ### `ERR\_CRYPTO\_UNKNOWN\_DH\_GROUP` An unknown Diffie-Hellman group name was given. See [`crypto.getDiffieHellman()`][] for a list of valid group names. ### `ERR\_CRYPTO\_UNSUPPORTED\_OPERATION` An attempt to invoke an unsupported crypto operation was made. ### `ERR\_DEBUGGER\_ERROR` An error occurred with the [debugger][]. ### `ERR\_DEBUGGER\_STARTUP\_ERROR` The [debugger][] timed out waiting for | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.011182716116309166,
0.05812237784266472,
-0.09189756959676743,
0.07162582129240036,
0.055424537509679794,
-0.09152072668075562,
-0.06197568029165268,
0.062039997428655624,
-0.022503485903143883,
-0.09965211153030396,
0.02668803744018078,
-0.050896719098091125,
-0.0034333516377955675,
-0... | 0.037503 |
unknown cipher was specified. ### `ERR\_CRYPTO\_UNKNOWN\_DH\_GROUP` An unknown Diffie-Hellman group name was given. See [`crypto.getDiffieHellman()`][] for a list of valid group names. ### `ERR\_CRYPTO\_UNSUPPORTED\_OPERATION` An attempt to invoke an unsupported crypto operation was made. ### `ERR\_DEBUGGER\_ERROR` An error occurred with the [debugger][]. ### `ERR\_DEBUGGER\_STARTUP\_ERROR` The [debugger][] timed out waiting for the required host/port to be free. ### `ERR\_DIR\_CLOSED` The [`fs.Dir`][] was previously closed. ### `ERR\_DIR\_CONCURRENT\_OPERATION` A synchronous read or close call was attempted on an [`fs.Dir`][] which has ongoing asynchronous operations. ### `ERR\_DLOPEN\_DISABLED` Loading native addons has been disabled using [`--no-addons`][]. ### `ERR\_DLOPEN\_FAILED` A call to `process.dlopen()` failed. ### `ERR\_DNS\_SET\_SERVERS\_FAILED` `c-ares` failed to set the DNS server. ### `ERR\_DOMAIN\_CALLBACK\_NOT\_AVAILABLE` The `node:domain` module was not usable since it could not establish the required error handling hooks, because [`process.setUncaughtExceptionCaptureCallback()`][] had been called at an earlier point in time. ### `ERR\_DOMAIN\_CANNOT\_SET\_UNCAUGHT\_EXCEPTION\_CAPTURE` [`process.setUncaughtExceptionCaptureCallback()`][] could not be called because the `node:domain` module has been loaded at an earlier point in time. The stack trace is extended to include the point in time at which the `node:domain` module had been loaded. ### `ERR\_DUPLICATE\_STARTUP\_SNAPSHOT\_MAIN\_FUNCTION` [`v8.startupSnapshot.setDeserializeMainFunction()`][] could not be called because it had already been called before. ### `ERR\_ENCODING\_INVALID\_ENCODED\_DATA` Data provided to `TextDecoder()` API was invalid according to the encoding provided. ### `ERR\_ENCODING\_NOT\_SUPPORTED` Encoding provided to `TextDecoder()` API was not one of the [WHATWG Supported Encodings][]. ### `ERR\_EVAL\_ESM\_CANNOT\_PRINT` `--print` cannot be used with ESM input. ### `ERR\_EVENT\_RECURSION` Thrown when an attempt is made to recursively dispatch an event on `EventTarget`. ### `ERR\_EXECUTION\_ENVIRONMENT\_NOT\_AVAILABLE` The JS execution context is not associated with a Node.js environment. This may occur when Node.js is used as an embedded library and some hooks for the JS engine are not set up properly. ### `ERR\_FALSY\_VALUE\_REJECTION` A `Promise` that was callbackified via `util.callbackify()` was rejected with a falsy value. ### `ERR\_FEATURE\_UNAVAILABLE\_ON\_PLATFORM` Used when a feature that is not available to the current platform which is running Node.js is used. ### `ERR\_FS\_CP\_DIR\_TO\_NON\_DIR` An attempt was made to copy a directory to a non-directory (file, symlink, etc.) using [`fs.cp()`][]. ### `ERR\_FS\_CP\_EEXIST` An attempt was made to copy over a file that already existed with [`fs.cp()`][], with the `force` and `errorOnExist` set to `true`. ### `ERR\_FS\_CP\_EINVAL` When using [`fs.cp()`][], `src` or `dest` pointed to an invalid path. ### `ERR\_FS\_CP\_FIFO\_PIPE` An attempt was made to copy a named pipe with [`fs.cp()`][]. ### `ERR\_FS\_CP\_NON\_DIR\_TO\_DIR` An attempt was made to copy a non-directory (file, symlink, etc.) to a directory using [`fs.cp()`][]. ### `ERR\_FS\_CP\_SOCKET` An attempt was made to copy to a socket with [`fs.cp()`][]. ### `ERR\_FS\_CP\_SYMLINK\_TO\_SUBDIRECTORY` When using [`fs.cp()`][], a symlink in `dest` pointed to a subdirectory of `src`. ### `ERR\_FS\_CP\_UNKNOWN` An attempt was made to copy to an unknown file type with [`fs.cp()`][]. ### `ERR\_FS\_EISDIR` Path is a directory. ### `ERR\_FS\_FILE\_TOO\_LARGE` An attempt was made to read a file larger than the supported 2 GiB limit for `fs.readFile()`. This is not a limitation of `Buffer`, but an internal I/O constraint. For handling larger files, consider using `fs.createReadStream()` to read the file in chunks. ### `ERR\_FS\_WATCH\_QUEUE\_OVERFLOW` The number of file system events queued without being handled exceeded the size specified in `maxQueue` in `fs.watch()`. ### `ERR\_HTTP2\_ALTSVC\_INVALID\_ORIGIN` HTTP/2 ALTSVC frames require a valid origin. ### `ERR\_HTTP2\_ALTSVC\_LENGTH` HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes. ### `ERR\_HTTP2\_CONNECT\_AUTHORITY` For HTTP/2 requests using the `CONNECT` method, the `:authority` pseudo-header is required. ### `ERR\_HTTP2\_CONNECT\_PATH` For HTTP/2 requests using the `CONNECT` method, the `:path` pseudo-header is forbidden. ### `ERR\_HTTP2\_CONNECT\_SCHEME` For HTTP/2 requests using the `CONNECT` method, the `:scheme` pseudo-header is forbidden. ### `ERR\_HTTP2\_ERROR` A non-specific HTTP/2 error has occurred. ### `ERR\_HTTP2\_GOAWAY\_SESSION` New HTTP/2 Streams may not be opened after the `Http2Session` has received a | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.09884605556726456,
0.0536111481487751,
-0.05791372060775757,
0.034581564366817474,
0.03067348524928093,
-0.10173151642084122,
-0.04368463158607483,
-0.05653514713048935,
-0.004530230071395636,
0.00980209931731224,
0.08426576852798462,
-0.05384346470236778,
-0.04596666991710663,
0.041680... | 0.050567 |
`ERR\_HTTP2\_CONNECT\_PATH` For HTTP/2 requests using the `CONNECT` method, the `:path` pseudo-header is forbidden. ### `ERR\_HTTP2\_CONNECT\_SCHEME` For HTTP/2 requests using the `CONNECT` method, the `:scheme` pseudo-header is forbidden. ### `ERR\_HTTP2\_ERROR` A non-specific HTTP/2 error has occurred. ### `ERR\_HTTP2\_GOAWAY\_SESSION` New HTTP/2 Streams may not be opened after the `Http2Session` has received a `GOAWAY` frame from the connected peer. ### `ERR\_HTTP2\_HEADERS\_AFTER\_RESPOND` An additional headers was specified after an HTTP/2 response was initiated. ### `ERR\_HTTP2\_HEADERS\_SENT` An attempt was made to send multiple response headers. ### `ERR\_HTTP2\_HEADER\_SINGLE\_VALUE` Multiple values were provided for an HTTP/2 header field that was required to have only a single value. ### `ERR\_HTTP2\_INFO\_STATUS\_NOT\_ALLOWED` Informational HTTP status codes (`1xx`) may not be set as the response status code on HTTP/2 responses. ### `ERR\_HTTP2\_INVALID\_CONNECTION\_HEADERS` HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses. ### `ERR\_HTTP2\_INVALID\_HEADER\_VALUE` An invalid HTTP/2 header value was specified. ### `ERR\_HTTP2\_INVALID\_INFO\_STATUS` An invalid HTTP informational status code has been specified. Informational status codes must be an integer between `100` and `199` (inclusive). ### `ERR\_HTTP2\_INVALID\_ORIGIN` HTTP/2 `ORIGIN` frames require a valid origin. ### `ERR\_HTTP2\_INVALID\_PACKED\_SETTINGS\_LENGTH` Input `Buffer` and `Uint8Array` instances passed to the `http2.getUnpackedSettings()` API must have a length that is a multiple of six. ### `ERR\_HTTP2\_INVALID\_PSEUDOHEADER` Only valid HTTP/2 pseudoheaders (`:status`, `:path`, `:authority`, `:scheme`, and `:method`) may be used. ### `ERR\_HTTP2\_INVALID\_SESSION` An action was performed on an `Http2Session` object that had already been destroyed. ### `ERR\_HTTP2\_INVALID\_SETTING\_VALUE` An invalid value has been specified for an HTTP/2 setting. ### `ERR\_HTTP2\_INVALID\_STREAM` An operation was performed on a stream that had already been destroyed. ### `ERR\_HTTP2\_MAX\_PENDING\_SETTINGS\_ACK` Whenever an HTTP/2 `SETTINGS` frame is sent to a connected peer, the peer is required to send an acknowledgment that it has received and applied the new `SETTINGS`. By default, a maximum number of unacknowledged `SETTINGS` frames may be sent at any given time. This error code is used when that limit has been reached. ### `ERR\_HTTP2\_NESTED\_PUSH` An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted. ### `ERR\_HTTP2\_NO\_MEM` Out of memory when using the `http2session.setLocalWindowSize(windowSize)` API. ### `ERR\_HTTP2\_NO\_SOCKET\_MANIPULATION` An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an `Http2Session`. ### `ERR\_HTTP2\_ORIGIN\_LENGTH` HTTP/2 `ORIGIN` frames are limited to a length of 16382 bytes. ### `ERR\_HTTP2\_OUT\_OF\_STREAMS` The number of streams created on a single HTTP/2 session reached the maximum limit. ### `ERR\_HTTP2\_PAYLOAD\_FORBIDDEN` A message payload was specified for an HTTP response code for which a payload is forbidden. ### `ERR\_HTTP2\_PING\_CANCEL` An HTTP/2 ping was canceled. ### `ERR\_HTTP2\_PING\_LENGTH` HTTP/2 ping payloads must be exactly 8 bytes in length. ### `ERR\_HTTP2\_PSEUDOHEADER\_NOT\_ALLOWED` An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the `:` prefix. ### `ERR\_HTTP2\_PUSH\_DISABLED` An attempt was made to create a push stream, which had been disabled by the client. ### `ERR\_HTTP2\_SEND\_FILE` An attempt was made to use the `Http2Stream.prototype.responseWithFile()` API to send a directory. ### `ERR\_HTTP2\_SEND\_FILE\_NOSEEK` An attempt was made to use the `Http2Stream.prototype.responseWithFile()` API to send something other than a regular file, but `offset` or `length` options were provided. ### `ERR\_HTTP2\_SESSION\_ERROR` The `Http2Session` closed with a non-zero error code. ### `ERR\_HTTP2\_SETTINGS\_CANCEL` The `Http2Session` settings canceled. ### `ERR\_HTTP2\_SOCKET\_BOUND` An attempt was made to connect a `Http2Session` object to a `net.Socket` or `tls.TLSSocket` that had already been bound to another `Http2Session` object. ### `ERR\_HTTP2\_SOCKET\_UNBOUND` An attempt was made to use the `socket` property of an `Http2Session` that has already been closed. ### `ERR\_HTTP2\_STATUS\_101` Use of the `101` Informational status code is forbidden in HTTP/2. ### `ERR\_HTTP2\_STATUS\_INVALID` An invalid HTTP status code has been specified. Status codes must be an integer between `100` | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.043647650629282,
-0.012857827357947826,
-0.06306590139865875,
-0.05229335278272629,
-0.0028638625517487526,
-0.06277959793806076,
-0.017286263406276703,
-0.02124519646167755,
0.022597309201955795,
0.03641591593623161,
-0.012640094384551048,
-0.012793893925845623,
0.009941576048731804,
0... | 0.046405 |
### `ERR\_HTTP2\_SOCKET\_UNBOUND` An attempt was made to use the `socket` property of an `Http2Session` that has already been closed. ### `ERR\_HTTP2\_STATUS\_101` Use of the `101` Informational status code is forbidden in HTTP/2. ### `ERR\_HTTP2\_STATUS\_INVALID` An invalid HTTP status code has been specified. Status codes must be an integer between `100` and `599` (inclusive). ### `ERR\_HTTP2\_STREAM\_CANCEL` An `Http2Stream` was destroyed before any data was transmitted to the connected peer. ### `ERR\_HTTP2\_STREAM\_ERROR` A non-zero error code was been specified in an `RST\_STREAM` frame. ### `ERR\_HTTP2\_STREAM\_SELF\_DEPENDENCY` When setting the priority for an HTTP/2 stream, the stream may be marked as a dependency for a parent stream. This error code is used when an attempt is made to mark a stream and dependent of itself. ### `ERR\_HTTP2\_TOO\_MANY\_CUSTOM\_SETTINGS` The number of supported custom settings (10) has been exceeded. ### `ERR\_HTTP2\_TOO\_MANY\_INVALID\_FRAMES` The limit of acceptable invalid HTTP/2 protocol frames sent by the peer, as specified through the `maxSessionInvalidFrames` option, has been exceeded. ### `ERR\_HTTP2\_TRAILERS\_ALREADY\_SENT` Trailing headers have already been sent on the `Http2Stream`. ### `ERR\_HTTP2\_TRAILERS\_NOT\_READY` The `http2stream.sendTrailers()` method cannot be called until after the `'wantTrailers'` event is emitted on an `Http2Stream` object. The `'wantTrailers'` event will only be emitted if the `waitForTrailers` option is set for the `Http2Stream`. ### `ERR\_HTTP2\_UNSUPPORTED\_PROTOCOL` `http2.connect()` was passed a URL that uses any protocol other than `http:` or `https:`. ### `ERR\_HTTP\_BODY\_NOT\_ALLOWED` An error is thrown when writing to an HTTP response which does not allow contents. ### `ERR\_HTTP\_CONTENT\_LENGTH\_MISMATCH` Response body size doesn't match with the specified content-length header value. ### `ERR\_HTTP\_HEADERS\_SENT` An attempt was made to add more headers after the headers had already been sent. ### `ERR\_HTTP\_INVALID\_HEADER\_VALUE` An invalid HTTP header value was specified. ### `ERR\_HTTP\_INVALID\_STATUS\_CODE` Status code was outside the regular status code range (100-999). ### `ERR\_HTTP\_REQUEST\_TIMEOUT` The client has not sent the entire request within the allowed time. ### `ERR\_HTTP\_SOCKET\_ASSIGNED` The given [`ServerResponse`][] was already assigned a socket. ### `ERR\_HTTP\_SOCKET\_ENCODING` Changing the socket encoding is not allowed per [RFC 7230 Section 3][]. ### `ERR\_HTTP\_TRAILER\_INVALID` The `Trailer` header was set even though the transfer encoding does not support that. ### `ERR\_ILLEGAL\_CONSTRUCTOR` An attempt was made to construct an object using a non-public constructor. ### `ERR\_IMPORT\_ATTRIBUTE\_MISSING` An import attribute is missing, preventing the specified module to be imported. ### `ERR\_IMPORT\_ATTRIBUTE\_TYPE\_INCOMPATIBLE` An import `type` attribute was provided, but the specified module is of a different type. ### `ERR\_IMPORT\_ATTRIBUTE\_UNSUPPORTED` An import attribute is not supported by this version of Node.js. ### `ERR\_INCOMPATIBLE\_OPTION\_PAIR` An option pair is incompatible with each other and cannot be used at the same time. ### `ERR\_INPUT\_TYPE\_NOT\_ALLOWED` The `--input-type` flag was used to attempt to execute a file. This flag can only be used with input via `--eval`, `--print`, or `STDIN`. ### `ERR\_INSPECTOR\_ALREADY\_ACTIVATED` While using the `node:inspector` module, an attempt was made to activate the inspector when it already started to listen on a port. Use `inspector.close()` before activating it on a different address. ### `ERR\_INSPECTOR\_ALREADY\_CONNECTED` While using the `node:inspector` module, an attempt was made to connect when the inspector was already connected. ### `ERR\_INSPECTOR\_CLOSED` While using the `node:inspector` module, an attempt was made to use the inspector after the session had already closed. ### `ERR\_INSPECTOR\_COMMAND` An error occurred while issuing a command via the `node:inspector` module. ### `ERR\_INSPECTOR\_NOT\_ACTIVE` The `inspector` is not active when `inspector.waitForDebugger()` is called. ### `ERR\_INSPECTOR\_NOT\_AVAILABLE` The `node:inspector` module is not available for use. ### `ERR\_INSPECTOR\_NOT\_CONNECTED` While using the `node:inspector` module, an attempt was made to use the inspector before it was connected. ### `ERR\_INSPECTOR\_NOT\_WORKER` An API was called on the main thread that can only be used from the worker thread. ### `ERR\_INTERNAL\_ASSERTION` There was a bug in Node.js or incorrect usage of Node.js | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.06568393856287003,
0.017818540334701538,
-0.04515776410698891,
-0.06392990052700043,
0.018977463245391846,
-0.06106553599238396,
-0.024006372317671776,
0.02215006574988365,
0.02033054269850254,
0.05612141638994217,
0.03689063712954521,
0.02464146725833416,
-0.012041039764881134,
0.03980... | 0.096003 |
`ERR\_INSPECTOR\_NOT\_CONNECTED` While using the `node:inspector` module, an attempt was made to use the inspector before it was connected. ### `ERR\_INSPECTOR\_NOT\_WORKER` An API was called on the main thread that can only be used from the worker thread. ### `ERR\_INTERNAL\_ASSERTION` There was a bug in Node.js or incorrect usage of Node.js internals. To fix the error, open an issue at . ### `ERR\_INVALID\_ADDRESS` The provided address is not understood by the Node.js API. ### `ERR\_INVALID\_ADDRESS\_FAMILY` The provided address family is not understood by the Node.js API. ### `ERR\_INVALID\_ARG\_TYPE` An argument of the wrong type was passed to a Node.js API. ### `ERR\_INVALID\_ARG\_VALUE` An invalid or unsupported value was passed for a given argument. ### `ERR\_INVALID\_ASYNC\_ID` An invalid `asyncId` or `triggerAsyncId` was passed using `AsyncHooks`. An id less than -1 should never happen. ### `ERR\_INVALID\_BUFFER\_SIZE` A swap was performed on a `Buffer` but its size was not compatible with the operation. ### `ERR\_INVALID\_CHAR` Invalid characters were detected in headers. ### `ERR\_INVALID\_CURSOR\_POS` A cursor on a given stream cannot be moved to a specified row without a specified column. ### `ERR\_INVALID\_FD` A file descriptor ('fd') was not valid (e.g. it was a negative value). ### `ERR\_INVALID\_FD\_TYPE` A file descriptor ('fd') type was not valid. ### `ERR\_INVALID\_FILE\_URL\_HOST` A Node.js API that consumes `file:` URLs (such as certain functions in the [`fs`][] module) encountered a file URL with an incompatible host. This situation can only occur on Unix-like systems where only `localhost` or an empty host is supported. ### `ERR\_INVALID\_FILE\_URL\_PATH` A Node.js API that consumes `file:` URLs (such as certain functions in the [`fs`][] module) encountered a file URL with an incompatible path. The exact semantics for determining whether a path can be used is platform-dependent. The thrown error object includes an `input` property that contains the URL object of the invalid `file:` URL. ### `ERR\_INVALID\_HANDLE\_TYPE` An attempt was made to send an unsupported "handle" over an IPC communication channel to a child process. See [`subprocess.send()`][] and [`process.send()`][] for more information. ### `ERR\_INVALID\_HTTP\_TOKEN` An invalid HTTP token was supplied. ### `ERR\_INVALID\_IP\_ADDRESS` An IP address is not valid. ### `ERR\_INVALID\_MIME\_SYNTAX` The syntax of a MIME is not valid. ### `ERR\_INVALID\_MODULE` An attempt was made to load a module that does not exist or was otherwise not valid. ### `ERR\_INVALID\_MODULE\_SPECIFIER` The imported module string is an invalid URL, package name, or package subpath specifier. ### `ERR\_INVALID\_OBJECT\_DEFINE\_PROPERTY` An error occurred while setting an invalid attribute on the property of an object. ### `ERR\_INVALID\_PACKAGE\_CONFIG` An invalid [`package.json`][] file failed parsing. ### `ERR\_INVALID\_PACKAGE\_TARGET` The `package.json` [`"exports"`][] field contains an invalid target mapping value for the attempted module resolution. ### `ERR\_INVALID\_PROTOCOL` An invalid `options.protocol` was passed to `http.request()`. ### `ERR\_INVALID\_REPL\_EVAL\_CONFIG` Both `breakEvalOnSigint` and `eval` options were set in the [`REPL`][] config, which is not supported. ### `ERR\_INVALID\_REPL\_INPUT` The input may not be used in the [`REPL`][]. The conditions under which this error is used are described in the [`REPL`][] documentation. ### `ERR\_INVALID\_RETURN\_PROPERTY` Thrown in case a function option does not provide a valid value for one of its returned object properties on execution. ### `ERR\_INVALID\_RETURN\_PROPERTY\_VALUE` Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution. ### `ERR\_INVALID\_RETURN\_VALUE` Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise. ### `ERR\_INVALID\_STATE` Indicates that an operation cannot be completed due to an invalid state. For instance, an object may have already been destroyed, or may be performing another operation. ### `ERR\_INVALID\_SYNC\_FORK\_INPUT` A `Buffer`, `TypedArray`, `DataView`, or `string` was provided as stdio input to an asynchronous fork. | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.10321997106075287,
0.045243438333272934,
-0.016017595306038857,
0.0679735392332077,
0.06855779141187668,
-0.0869818925857544,
-0.04743414372205734,
-0.04184100404381752,
0.062320467084646225,
-0.010941682383418083,
-0.04606049880385399,
0.01768733188509941,
-0.005116576328873634,
-0.001... | 0.119568 |
to return a promise. ### `ERR\_INVALID\_STATE` Indicates that an operation cannot be completed due to an invalid state. For instance, an object may have already been destroyed, or may be performing another operation. ### `ERR\_INVALID\_SYNC\_FORK\_INPUT` A `Buffer`, `TypedArray`, `DataView`, or `string` was provided as stdio input to an asynchronous fork. See the documentation for the [`child\_process`][] module for more information. ### `ERR\_INVALID\_THIS` A Node.js API function was called with an incompatible `this` value. ```js const urlSearchParams = new URLSearchParams('foo=bar&baz=new'); const buf = Buffer.alloc(1); urlSearchParams.has.call(buf, 'foo'); // Throws a TypeError with code 'ERR\_INVALID\_THIS' ``` ### `ERR\_INVALID\_TUPLE` An element in the `iterable` provided to the [WHATWG][WHATWG URL API] [`URLSearchParams` constructor][`new URLSearchParams(iterable)`] did not represent a `[name, value]` tuple – that is, if an element is not iterable, or does not consist of exactly two elements. ### `ERR\_INVALID\_TYPESCRIPT\_SYNTAX` The provided TypeScript syntax is not valid. ### `ERR\_INVALID\_URI` An invalid URI was passed. ### `ERR\_INVALID\_URL` An invalid URL was passed to the [WHATWG][WHATWG URL API] [`URL` constructor][`new URL(input)`] or the legacy [`url.parse()`][] to be parsed. The thrown error object typically has an additional property `'input'` that contains the URL that failed to parse. ### `ERR\_INVALID\_URL\_PATTERN` An invalid URLPattern was passed to the [WHATWG][WHATWG URL API] [`URLPattern` constructor][`new URLPattern(input)`] to be parsed. ### `ERR\_INVALID\_URL\_SCHEME` An attempt was made to use a URL of an incompatible scheme (protocol) for a specific purpose. It is only used in the [WHATWG URL API][] support in the [`fs`][] module (which only accepts URLs with `'file'` scheme), but may be used in other Node.js APIs as well in the future. ### `ERR\_IPC\_CHANNEL\_CLOSED` An attempt was made to use an IPC communication channel that was already closed. ### `ERR\_IPC\_DISCONNECTED` An attempt was made to disconnect an IPC communication channel that was already disconnected. See the documentation for the [`child\_process`][] module for more information. ### `ERR\_IPC\_ONE\_PIPE` An attempt was made to create a child Node.js process using more than one IPC communication channel. See the documentation for the [`child\_process`][] module for more information. ### `ERR\_IPC\_SYNC\_FORK` An attempt was made to open an IPC communication channel with a synchronously forked Node.js process. See the documentation for the [`child\_process`][] module for more information. ### `ERR\_IP\_BLOCKED` IP is blocked by `net.BlockList`. ### `ERR\_LOADER\_CHAIN\_INCOMPLETE` An ESM loader hook returned without calling `next()` and without explicitly signaling a short circuit. ### `ERR\_LOAD\_SQLITE\_EXTENSION` An error occurred while loading a SQLite extension. ### `ERR\_MEMORY\_ALLOCATION\_FAILED` An attempt was made to allocate memory (usually in the C++ layer) but it failed. ### `ERR\_MESSAGE\_TARGET\_CONTEXT\_UNAVAILABLE` A message posted to a [`MessagePort`][] could not be deserialized in the target [vm][] `Context`. Not all Node.js objects can be successfully instantiated in any context at this time, and attempting to transfer them using `postMessage()` can fail on the receiving side in that case. ### `ERR\_METHOD\_NOT\_IMPLEMENTED` A method is required but not implemented. ### `ERR\_MISSING\_ARGS` A required argument of a Node.js API was not passed. This is only used for strict compliance with the API specification (which in some cases may accept `func(undefined)` but not `func()`). In most native Node.js APIs, `func(undefined)` and `func()` are treated identically, and the [`ERR\_INVALID\_ARG\_TYPE`][] error code may be used instead. ### `ERR\_MISSING\_OPTION` For APIs that accept options objects, some options might be mandatory. This code is thrown if a required option is missing. ### `ERR\_MISSING\_PASSPHRASE` An attempt was made to read an encrypted key without specifying a passphrase. ### `ERR\_MISSING\_PLATFORM\_FOR\_WORKER` The V8 platform used by this instance of Node.js does not support creating Workers. This is caused by lack of embedder support for Workers. In particular, this error will not occur with standard builds of Node.js. ### `ERR\_MODULE\_LINK\_MISMATCH` A module can | https://github.com/nodejs/node/blob/main//doc/api/errors.md | main | nodejs | [
-0.11484553664922714,
0.02760939672589302,
0.0035225767642259598,
0.0180983766913414,
-0.013695423491299152,
-0.029735879972577095,
0.0028440963942557573,
0.018846338614821434,
0.02259211800992489,
-0.028716454282402992,
-0.052199266850948334,
0.03663220256567001,
-0.05172374099493027,
-0.... | 0.09526 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.