node-addon-api
Advanced tools
Comparing version 1.3.0 to 1.4.0
# node-addon-api Changelog | ||
## 2018-05-08 Version 1.3.0 (Current), @mhdawson | ||
## 2018-07-19 Version 1.4.0 (Current), @NickNasso | ||
@@ -8,2 +8,44 @@ ### Notable changes: | ||
#### Documentation | ||
- Numerous additions to the documentation, filling out coverage | ||
of API surface | ||
#### API | ||
- Add resource parameters to AsyncWorker constructor | ||
- Add memory management feature | ||
### Commits | ||
* [[`7dc5ac8bc3`](https://github.com/nodejs/node-addon-api/commit/7dc5ac8bc3)] - **doc**: update metadata for release (Nicola Del Gobbo) | ||
* [[`d68e86adb4`](https://github.com/nodejs/node-addon-api/commit/d68e86adb4)] - **doc**: Added documentation for PropertyDescriptor (Anisha Rohra) [#309](https://github.com/nodejs/node-addon-api/pull/309) | ||
* [[`968a5f2000`](https://github.com/nodejs/node-addon-api/commit/968a5f2000)] - **doc**: Add documentation for ObjectReference.md (Anisha Rohra) [#307](https://github.com/nodejs/node-addon-api/pull/307) | ||
* [[`908cdc314c`](https://github.com/nodejs/node-addon-api/commit/908cdc314c)] - **doc**: add `TypedArray` and `TypedArrayOf` (Kyle Farnung) [#305](https://github.com/nodejs/node-addon-api/pull/305) | ||
* [[`2ff776ffe3`](https://github.com/nodejs/node-addon-api/commit/2ff776ffe3)] - backport node::Persistent (Gabriel Schulhof) [#300](https://github.com/nodejs/node-addon-api/pull/300) | ||
* [[`98161970c9`](https://github.com/nodejs/node-addon-api/commit/98161970c9)] - Backport perf, crash and exception handling fixes (Gabriel Schulhof) [#295](https://github.com/nodejs/node-addon-api/pull/295) | ||
* [[`dd1191e086`](https://github.com/nodejs/node-addon-api/commit/dd1191e086)] - **test**: fix asyncworker test so it runs on 6.x (Michael Dawson) [#298](https://github.com/nodejs/node-addon-api/pull/298) | ||
* [[`11697fcecd`](https://github.com/nodejs/node-addon-api/commit/11697fcecd)] - **doc**: ArrayBuffer and Buffer documentation (Kyle Farnung) [#256](https://github.com/nodejs/node-addon-api/pull/256) | ||
* [[`605aa2babf`](https://github.com/nodejs/node-addon-api/commit/605aa2babf)] - Add memory management feature (NickNaso) [#286](https://github.com/nodejs/node-addon-api/pull/286) | ||
* [[`86be13a611`](https://github.com/nodejs/node-addon-api/commit/86be13a611)] - **doc**: Fix HandleScope docs (Ben Berman) [#287](https://github.com/nodejs/node-addon-api/pull/287) | ||
* [[`90f92c4dc0`](https://github.com/nodejs/node-addon-api/commit/90f92c4dc0)] - **doc**: Update broken links in README.md (Hitesh Kanwathirtha) [#290](https://github.com/nodejs/node-addon-api/pull/290) | ||
* [[`c2a620dc11`](https://github.com/nodejs/node-addon-api/commit/c2a620dc11)] - **doc**: Clarify positioning versus N-API (Michael Dawson) [#288](https://github.com/nodejs/node-addon-api/pull/288) | ||
* [[`6cff890ee5`](https://github.com/nodejs/node-addon-api/commit/6cff890ee5)] - **doc**: Fix typo in docs (Ben Berman) [#284](https://github.com/nodejs/node-addon-api/pull/284) | ||
* [[`7394bfd154`](https://github.com/nodejs/node-addon-api/commit/7394bfd154)] - **doc**: Fix typo in docs (Ben Berman) [#285](https://github.com/nodejs/node-addon-api/pull/285) | ||
* [[`12b2cdeed3`](https://github.com/nodejs/node-addon-api/commit/12b2cdeed3)] - fix test files (Kyle Farnung) [#257](https://github.com/nodejs/node-addon-api/pull/257) | ||
* [[`9ab6607242`](https://github.com/nodejs/node-addon-api/commit/9ab6607242)] - **doc**: Update Doc Version Number (joshgarde) [#277](https://github.com/nodejs/node-addon-api/pull/277) | ||
* [[`e029a076c6`](https://github.com/nodejs/node-addon-api/commit/e029a076c6)] - **doc**: First pass at basic Node Addon API docs (Hitesh Kanwathirtha) [#268](https://github.com/nodejs/node-addon-api/pull/268) | ||
* [[`74ff79717e`](https://github.com/nodejs/node-addon-api/commit/74ff79717e)] - **doc**: fix link to async\_worker.md (Michael Dawson) | ||
* [[`5a63f45eda`](https://github.com/nodejs/node-addon-api/commit/5a63f45eda)] - **doc**: First step of error and async doc (NickNaso) [#272](https://github.com/nodejs/node-addon-api/pull/272) | ||
* [[`9d38f61afb`](https://github.com/nodejs/node-addon-api/commit/9d38f61afb)] - **doc**: New Promise and Reference docs (Jim Schlight) [#243](https://github.com/nodejs/node-addon-api/pull/243) | ||
* [[`43ff9fa836`](https://github.com/nodejs/node-addon-api/commit/43ff9fa836)] - **doc**: Updated Object documentation (Anisha Rohra) [#254](https://github.com/nodejs/node-addon-api/pull/254) | ||
* [[`b197f7cc8b`](https://github.com/nodejs/node-addon-api/commit/b197f7cc8b)] - **doc**: minor typos (Nick Soggin) [#248](https://github.com/nodejs/node-addon-api/pull/248) | ||
* [[`4b8918b352`](https://github.com/nodejs/node-addon-api/commit/4b8918b352)] - Add resource parameters to AsyncWorker constructor (Jinho Bang) [#253](https://github.com/nodejs/node-addon-api/pull/253) | ||
* [[`1ecf7c19b6`](https://github.com/nodejs/node-addon-api/commit/1ecf7c19b6)] - **doc**: fix wrong link in readme (miloas) [#255](https://github.com/nodejs/node-addon-api/pull/255) | ||
* [[`a750ed1932`](https://github.com/nodejs/node-addon-api/commit/a750ed1932)] - **release**: updates to metadata for next release (Michael Dawson) | ||
## 2018-05-08 Version 1.3.0, @mhdawson | ||
### Notable changes: | ||
#### Documentation | ||
- Added documentation for Scopes | ||
@@ -10,0 +52,0 @@ - Added documentation for migration from NAN |
@@ -1,5 +0,129 @@ | ||
# Array buffer | ||
# ArrayBuffer | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
The `ArrayBuffer` class corresponds to the | ||
[JavaScript `ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | ||
class. | ||
## Methods | ||
### New | ||
Allocates a new `ArrayBuffer` instance with a given length. | ||
```cpp | ||
static ArrayBuffer New(napi_env env, size_t byteLength); | ||
``` | ||
- `[in] env`: The environment in which to create the `ArrayBuffer` instance. | ||
- `[in] byteLength`: The length to be allocated, in bytes. | ||
Returns a new `ArrayBuffer` instance. | ||
### New | ||
Wraps the provided external data into a new `ArrayBuffer` instance. | ||
The `ArrayBuffer` instance does not assume ownership for the data and expects it | ||
to be valid for the lifetime of the instance. Since the `ArrayBuffer` is subject | ||
to garbage collection this overload is only suitable for data which is static | ||
and never needs to be freed. | ||
```cpp | ||
static ArrayBuffer New(napi_env env, void* externalData, size_t byteLength); | ||
``` | ||
- `[in] env`: The environment in which to create the `ArrayBuffer` instance. | ||
- `[in] externalData`: The pointer to the external data to wrap. | ||
- `[in] byteLength`: The length of the `externalData`, in bytes. | ||
Returns a new `ArrayBuffer` instance. | ||
### New | ||
Wraps the provided external data into a new `ArrayBuffer` instance. | ||
The `ArrayBuffer` instance does not assume ownership for the data and expects it | ||
to be valid for the lifetime of the instance. The data can only be freed once | ||
the `finalizeCallback` is invoked to indicate that the `ArrayBuffer` has been | ||
released. | ||
```cpp | ||
template <typename Finalizer> | ||
static ArrayBuffer New(napi_env env, | ||
void* externalData, | ||
size_t byteLength, | ||
Finalizer finalizeCallback); | ||
``` | ||
- `[in] env`: The environment in which to create the `ArrayBuffer` instance. | ||
- `[in] externalData`: The pointer to the external data to wrap. | ||
- `[in] byteLength`: The length of the `externalData`, in bytes. | ||
- `[in] finalizeCallback`: A function to be called when the `ArrayBuffer` is | ||
destroyed. It must implement `operator()`, accept a `void*` (which is the | ||
`externalData` pointer), and return `void`. | ||
Returns a new `ArrayBuffer` instance. | ||
### New | ||
Wraps the provided external data into a new `ArrayBuffer` instance. | ||
The `ArrayBuffer` instance does not assume ownership for the data and expects it | ||
to be valid for the lifetime of the instance. The data can only be freed once | ||
the `finalizeCallback` is invoked to indicate that the `ArrayBuffer` has been | ||
released. | ||
```cpp | ||
template <typename Finalizer, typename Hint> | ||
static ArrayBuffer New(napi_env env, | ||
void* externalData, | ||
size_t byteLength, | ||
Finalizer finalizeCallback, | ||
Hint* finalizeHint); | ||
``` | ||
- `[in] env`: The environment in which to create the `ArrayBuffer` instance. | ||
- `[in] externalData`: The pointer to the external data to wrap. | ||
- `[in] byteLength`: The length of the `externalData`, in bytes. | ||
- `[in] finalizeCallback`: The function to be called when the `ArrayBuffer` is | ||
destroyed. It must implement `operator()`, accept a `void*` (which is the | ||
`externalData` pointer) and `Hint*`, and return `void`. | ||
- `[in] finalizeHint`: The hint to be passed as the second parameter of the | ||
finalize callback. | ||
Returns a new `ArrayBuffer` instance. | ||
### Constructor | ||
Initializes an empty instance of the `ArrayBuffer` class. | ||
```cpp | ||
ArrayBuffer(); | ||
``` | ||
### Constructor | ||
Initializes a wrapper instance of an existing `ArrayBuffer` object. | ||
```cpp | ||
ArrayBuffer(napi_env env, napi_value value); | ||
``` | ||
- `[in] env`: The environment in which to create the `ArrayBuffer` instance. | ||
- `[in] value`: The `ArrayBuffer` reference to wrap. | ||
### ByteLength | ||
```cpp | ||
size_t ByteLength() const; | ||
``` | ||
Returns the length of the wrapped data, in bytes. | ||
### Data | ||
```cpp | ||
T* Data() const; | ||
``` | ||
Returns a pointer the wrapped data. |
# Asynchronous operations | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
Node.js native add-ons often need to execute long running tasks and to avoid | ||
blocking the **event loop** they have to run them asynchronously from the | ||
**event loop**. | ||
In the Node.js model of execution the event loop thread represents the thread | ||
where JavaScript code is executing. The node.js guidance is to avoid blocking | ||
other work queued on the event loop thread. Therefore, we need to do this work on | ||
another thread. | ||
All this means that native add-ons 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. | ||
Node Addon API provides an interface to support functions that cover | ||
the most common asynchronous use cases. There is an abstract classes to implement | ||
asynchronous operations: | ||
- **[AsyncWorker](async_worker.md)** | ||
These class helps manage asynchronous operations through an abstraction | ||
of the concept of moving data between the **event loop** and **worker threads**. |
@@ -1,5 +0,306 @@ | ||
# Async worker | ||
# AsyncWorker | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
`AsyncWorker` is an abstract class that you can subclass to remove many of the | ||
tedious tasks of moving data between the event loop and worker threads. This | ||
class internally handles all the details of creating and executing an asynchronous | ||
operation. | ||
Once created, execution is requested by calling `Queue`. When a thread is | ||
available for execution the `Execute` method will be invoked. Once `Execute` | ||
complets either `OnOK` or `OnError` will be invoked. Once the `OnOK` or | ||
`OnError` methods are complete the AsyncWorker instance is destructed. | ||
For the most basic use, only the `Execute` method must be implemented in a | ||
subclass. | ||
## Methods | ||
### Env | ||
Requests the environment in which the async worker has been initially created. | ||
```cpp | ||
Env Env() const; | ||
``` | ||
Returns the environment in which the async worker has been created. | ||
### Queue | ||
Requests that the work be queued for execution. | ||
```cpp | ||
void Queue(); | ||
``` | ||
### Cancel | ||
Cancels queued work if it has not yet been started. If it has already started | ||
executing, it cannot be cancelled. If cancelled successfully neither | ||
`OnOK` nor `OnError` will be called. | ||
```cpp | ||
void Cancel(); | ||
``` | ||
### Receiver | ||
```cpp | ||
ObjectReference& Receiver(); | ||
``` | ||
Returns the persistent object reference of the receiver object set when the async | ||
worker was created. | ||
### Callback | ||
```cpp | ||
FunctionReference& Callback(); | ||
``` | ||
Returns the persistent function reference of the callback set when the async | ||
worker was created. The returned function reference will receive the results of | ||
the computation that happened in the `Execute` method, unless the default | ||
implementation of `OnOK` or `OnError` is overridden. | ||
### SetError | ||
Sets the error message for the error that happened during the execution. Setting | ||
an error message will cause the `OnError` method to be invoked instead of `OnOK` | ||
once the `Execute` method completes. | ||
```cpp | ||
void SetError(const std::string& error); | ||
``` | ||
- `[in] error`: The reference to the string that represent the message of the error. | ||
### Execute | ||
This method is used to execute some tasks out of the **event loop** on a libuv | ||
worker thread. Subclasses must implement this method and the method is run on | ||
a thread other than that running the main event loop. As the method is not | ||
running on the main event loop, it must avoid calling any methods from node-addon-api | ||
or running any code that might invoke JavaScript. Instead once this method is | ||
complete any interaction through node-addon-api with JavaScript should be implemented | ||
in the `OnOK` method which runs on the main thread and is invoked when the `Execute` | ||
method completes. | ||
```cpp | ||
virtual void Execute() = 0; | ||
``` | ||
### OnOK | ||
This method is invoked when the computation in the `Excecute` method ends. | ||
The default implementation runs the Callback provided when the AsyncWorker class | ||
was created. | ||
```cpp | ||
virtual void OnOK(); | ||
``` | ||
### OnError | ||
This method is invoked afer Execute() completes if an error occurs | ||
while `Execute` is running and C++ exceptions are enabled or if an | ||
error was set through a call to `SetError`. The default implementation | ||
calls the callback provided when the AsyncWorker class was created, passing | ||
in the error as the first parameter. | ||
```cpp | ||
virtual void OnError(const Error& e); | ||
``` | ||
### Constructor | ||
Creates a new `AsyncWorker`. | ||
```cpp | ||
explicit AsyncWorker(const Function& callback); | ||
``` | ||
- `[in] callback`: The function which will be called when an asynchronous | ||
operations ends. The given function is called from the main event loop thread. | ||
Returns an AsyncWork instance which can later be queued for execution by calling | ||
`Queue`. | ||
### Constructor | ||
Creates a new `AsyncWorker`. | ||
```cpp | ||
explicit AsyncWorker(const Function& callback, const char* resource_name); | ||
``` | ||
- `[in] callback`: The function which will be called when an asynchronous | ||
operations ends. The given function is called from the main event loop thread. | ||
- `[in] resource_name`: Null-terminated strings that represents the | ||
identifier for the kind of resource that is being provided for diagnostic | ||
information exposed by the async_hooks API. | ||
Returns an AsyncWork instance which can later be queued for execution by calling | ||
`Queue`. | ||
### Constructor | ||
Creates a new `AsyncWorker`. | ||
```cpp | ||
explicit AsyncWorker(const Function& callback, const char* resource_name, const Object& resource); | ||
``` | ||
- `[in] callback`: The function which will be called when an asynchronous | ||
operations ends. The given function is called from the main event loop thread. | ||
- `[in] resource_name`: Null-terminated strings that represents the | ||
identifier for the kind of resource that is being provided for diagnostic | ||
information exposed by the async_hooks API. | ||
- `[in] resource`: Object associated with the asynchronous operation that | ||
will be passed to possible async_hooks. | ||
Returns an AsyncWork instance which can later be queued for execution by calling | ||
`Queue`. | ||
### Constructor | ||
Creates a new `AsyncWorker`. | ||
```cpp | ||
explicit AsyncWorker(const Object& receiver, const Function& callback); | ||
``` | ||
- `[in] receiver`: The `this` object passed to the called function. | ||
- `[in] callback`: The function which will be called when an asynchronous | ||
operations ends. The given function is called from the main event loop thread. | ||
Returns an AsyncWork instance which can later be queued for execution by calling | ||
`Queue`. | ||
### Constructor | ||
Creates a new `AsyncWorker`. | ||
```cpp | ||
explicit AsyncWorker(const Object& receiver, const Function& callback,const char* resource_name); | ||
``` | ||
- `[in] receiver`: The `this` object passed to the called function. | ||
- `[in] callback`: The function which will be called when an asynchronous | ||
operations ends. The given function is called from the main event loop thread. | ||
- `[in] resource_name`: Null-terminated strings that represents the | ||
identifier for the kind of resource that is being provided for diagnostic | ||
information exposed by the async_hooks API. | ||
Returns an AsyncWork instance which can later be queued for execution by calling | ||
`Queue`. | ||
### Constructor | ||
Creates a new `AsyncWorker`. | ||
```cpp | ||
explicit AsyncWorker(const Object& receiver, const Function& callback, const char* resource_name, const Object& resource); | ||
``` | ||
- `[in] receiver`: The `this` object passed to the called function. | ||
- `[in] callback`: The function which will be called when an asynchronous | ||
operations ends. The given function is called from the main event loop thread. | ||
- `[in] resource_name`: Null-terminated strings that represents the | ||
identifier for the kind of resource that is being provided for diagnostic | ||
information exposed by the async_hooks API. | ||
- `[in] resource`: Object associated with the asynchronous operation that | ||
will be passed to possible async_hooks. | ||
Returns an AsyncWork instance which can later be queued for execution by calling | ||
`Queue`. | ||
### Destructor | ||
Deletes the created work object that is used to execute logic asynchronously. | ||
```cpp | ||
virtual ~AsyncWorker(); | ||
``` | ||
## Operator | ||
```cpp | ||
operator napi_async_work() const; | ||
``` | ||
Returns the N-API napi_async_work wrapped by the AsyncWorker object. This can be | ||
used to mix usage of the C N-API and node-addon-api. | ||
## Example | ||
The first step to use the `AsyncWorker` class is to create a new class that inherit | ||
from it and implement the `Execute` abstract method. Typically input to your | ||
worker will be saved within class' fields generally passed in through its | ||
constructor. | ||
When the `Execute` method completes without errors the `OnOK` function callback | ||
will be invoked. In this function the results of the computation will be | ||
reassembled and returned back to the initial JavaScript context. | ||
`AsyncWorker` ensures that all the code in the `Execute` function runs in the | ||
background out of the **event loop** thread and at the end the `OnOK` or `OnError` | ||
function will be called and are executed as part of the event loop. | ||
The code below show a basic example of `AsyncWorker` the implementation: | ||
```cpp | ||
#include<napi.h> | ||
#include <chrono> | ||
#include <thread> | ||
use namespace Napi; | ||
class EchoWorker : public AsyncWorker { | ||
public: | ||
EchoWorker(Function& callback, std::string& echo) | ||
: AsyncWorker(callback), echo(echo) {} | ||
~EchoWorker() {} | ||
// This code will be executed on the worker thread | ||
void Execute() { | ||
// Need to simulate cpu heavy task | ||
std::this_thread::sleep_for(std::chrono::seconds(1)); | ||
} | ||
void OnOK() { | ||
HandleScope scope(Env()); | ||
Callback().Call({Env().Null(), String::New(Env(), echo)}); | ||
} | ||
private: | ||
std::string echo; | ||
}; | ||
``` | ||
The `EchoWorker`'s contructor calls the base class' constructor to pass in the | ||
callback that the `AsyncWorker` base class will store persistently. When the work | ||
on the `Execute` method is done the `OnOk` method is called and the results return | ||
back to JavaScript invoking the stored callback with its associated environment. | ||
The following code shows an example on how to create and and use an `AsyncWorker` | ||
```cpp | ||
Value Echo(const CallbackInfo& info) { | ||
// You need to check the input data here | ||
Function cb = info[1].As<Function>(); | ||
std::string in = info[0].As<String>(); | ||
EchoWorker* wk = new EchoWorker(cb, in); | ||
wk->Queue(); | ||
return info.Env().Undefined(); | ||
``` | ||
Using the implementation of an `AsyncWorker` is straight forward. You need only create | ||
a new instance and pass to its constructor the callback you want to execute when | ||
your asynchronous task ends and other data you need for your computation. Once created the | ||
only other action you have to do is to call the `Queue` method that will that will | ||
queue the created worker for execution. |
# Basic Types | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
Node Addon API consists of a few fundamental data types. These allow a user of | ||
the API to create, convert and introspect fundamental JavaScript types, and | ||
interoperate with their C++ counterparts. | ||
## Value | ||
Value is the base class of Node Addon API's fundamental object type hierarchy. | ||
It represents a JavaScript value of an unknown type. It is a thin wrapper around | ||
the N-API datatype `napi_value`. Methods on this class can be used to check | ||
the JavaScript type of the underlying N-API `napi_value` and also to convert to | ||
C++ types. | ||
### Constructor | ||
```cpp | ||
Value(); | ||
``` | ||
Used to create a Node Addon API `Value` that represents an **empty** value. | ||
```cpp | ||
Value(napi_env env, napi_value value); | ||
``` | ||
- `[in] env` - The `napi_env` environment in which to construct the Value | ||
object. | ||
- `[in] value` - The underlying JavaScript value that the `Value` instance | ||
represents. | ||
Returns a Node.js Addon API `Value` that represents the `napi_value` passed | ||
in. | ||
### Operators | ||
#### operator napi_value | ||
```cpp | ||
operator napi_value() const; | ||
``` | ||
Returns the underlying N-API `napi_value`. If the instance is _empty_, this | ||
returns `nullptr`. | ||
#### operator == | ||
```cpp | ||
bool operator ==(const Value& other) const; | ||
``` | ||
Returns `true` if this value strictly equals another value, or `false` otherwise. | ||
#### operator != | ||
```cpp | ||
bool operator !=(const Value& other) const; | ||
``` | ||
Returns `false` if this value strictly equals another value, or `true` otherwise. | ||
### Methods | ||
#### From | ||
```cpp | ||
template <typename T> | ||
static Value From(napi_env env, const T& value); | ||
``` | ||
- `[in] env` - The `napi_env` environment in which to construct the Value object. | ||
- `[in] value` - The C++ type to represent in JavaScript. | ||
Returns a `Napi::Value` representing the input C++ type in JavaScript. | ||
This method is used to convert from a C++ type to a JavaScript value. | ||
Here, `value` may be any of: | ||
- `bool` - returns a `Napi::Boolean`. | ||
- Any integer type - returns a `Napi::Number`. | ||
- Any floating point type - returns a `Napi::Number`. | ||
- `const char*` (encoded using UTF-8, null-terminated) - returns a `Napi::String`. | ||
- `const char16_t*` (encoded using UTF-16-LE, null-terminated) - returns a `Napi::String`. | ||
- `std::string` (encoded using UTF-8) - returns a `Napi::String`. | ||
- `std::u16string` - returns a `Napi::String`. | ||
- `napi::Value` - returns a `Napi::Value`. | ||
- `napi_value` - returns a `Napi::Value`. | ||
#### As | ||
```cpp | ||
template <typename T> T As() const; | ||
``` | ||
Returns the `Napi::Value` cast to a desired C++ type. | ||
Use this when the actual type is known or assumed. | ||
Note: | ||
This conversion does NOT coerce the type. Calling any methods inappropriate for | ||
the actual value type will throw `Napi::Error`. | ||
#### StrictEquals | ||
```cpp | ||
bool StrictEquals(const Value& other) const; | ||
``` | ||
- `[in] other` - The value to compare against. | ||
Returns true if the other `Napi::Value` is strictly equal to this one. | ||
#### Env | ||
```cpp | ||
Napi::Env Env() const; | ||
``` | ||
Returns the environment that the value is associated with. See | ||
[`Napi::Env`](env.md) for more details about environments. | ||
#### IsEmpty | ||
```cpp | ||
bool IsEmpty() const; | ||
``` | ||
Returns `true` if the value is uninitialized. | ||
An empty value is invalid, and most attempts to perform an operation on an | ||
empty value will result in an exception. An empty value is distinct from | ||
JavaScript `null` or `undefined`, which are valid values. | ||
When C++ exceptions are disabled at compile time, a method with a `Value` | ||
return type may return an empty value to indicate a pending exception. If C++ | ||
exceptions are not being used, callers should check the result of | ||
`Env::IsExceptionPending` before attempting to use the value. | ||
#### Type | ||
```cpp | ||
napi_valuetype Type() const; | ||
``` | ||
Returns the underlying N-API `napi_valuetype` of the value. | ||
#### IsUndefined | ||
```cpp | ||
bool IsUndefined() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `undefined` or `false` | ||
otherwise. | ||
#### IsNull | ||
```cpp | ||
bool IsNull() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `null` or `false` | ||
otherwise. | ||
#### IsBoolean | ||
```cpp | ||
bool IsBoolean() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `true` or JavaScript | ||
`false`, or `false` if the value is not a Boolean value in JavaScript. | ||
#### IsNumber | ||
```cpp | ||
bool IsNumber() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `Number` or `false` | ||
otherwise. | ||
#### IsString | ||
```cpp | ||
bool IsString() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `String` or `false` | ||
otherwise. | ||
#### IsSymbol | ||
```cpp | ||
bool IsSymbol() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `Symbol` or `false` | ||
otherwise. | ||
#### IsArray | ||
```cpp | ||
bool IsArray() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `Array` or `false` | ||
otherwise. | ||
#### IsArrayBuffer | ||
```cpp | ||
bool IsArrayBuffer() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `ArrayBuffer` or `false` | ||
otherwise. | ||
#### IsTypedArray | ||
```cpp | ||
bool IsTypedArray() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `TypedArray` or `false` | ||
otherwise. | ||
#### IsObject | ||
```cpp | ||
bool IsObject() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `Object` or `false` | ||
otherwise. | ||
#### IsFunction | ||
```cpp | ||
bool IsFunction() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `Function` or `false` | ||
otherwise. | ||
#### IsPromise | ||
```cpp | ||
bool IsPromise() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `Promise` or `false` | ||
otherwise. | ||
#### IsDataView | ||
```cpp | ||
bool IsDataView() const; | ||
``` | ||
Returns `true` if the underlying value is a JavaScript `DataView` or `false` | ||
otherwise. | ||
#### IsBuffer | ||
```cpp | ||
bool IsBuffer() const; | ||
``` | ||
Returns `true` if the underlying value is a Node.js `Buffer` or `false` | ||
otherwise. | ||
#### IsExternal | ||
```cpp | ||
bool IsExternal() const; | ||
``` | ||
Returns `true` if the underlying value is a N-API external object or `false` | ||
otherwise. | ||
#### ToBoolean | ||
```cpp | ||
Boolean ToBoolean() const; | ||
``` | ||
Returns a `Napi::Boolean` representing the `Napi::Value`. | ||
This is a wrapper around `napi_coerce_to_boolean`. This will throw a JavaScript | ||
exception if the coercion fails. If C++ exceptions are not being used, callers | ||
should check the result of `Env::IsExceptionPending` before attempting to use | ||
the returned value. | ||
#### ToNumber | ||
```cpp | ||
Number ToNumber() const; | ||
``` | ||
Returns a `Napi::Number` representing the `Napi::Value`. | ||
Note: | ||
This can cause script code to be executed according to JavaScript semantics. | ||
This is a wrapper around `napi_coerce_to_number`. This will throw a JavaScript | ||
exception if the coercion fails. If C++ exceptions are not being used, callers | ||
should check the result of `Env::IsExceptionPending` before attempting to use | ||
the returned value. | ||
#### ToString | ||
```cpp | ||
String ToString() const; | ||
``` | ||
Returns a `Napi::String` representing the `Napi::Value`. | ||
Note that this can cause script code to be executed according to JavaScript | ||
semantics. This is a wrapper around `napi_coerce_to_string`. This will throw a | ||
JavaScript exception if the coercion fails. If C++ exceptions are not being | ||
used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. | ||
#### ToObject | ||
```cpp | ||
Object ToObject() const; | ||
``` | ||
Returns a `Napi::Object` representing the `Napi::Value`. | ||
This is a wrapper around `napi_coerce_to_object`. This will throw a JavaScript | ||
exception if the coercion fails. If C++ exceptions are not being used, callers | ||
should check the result of `Env::IsExceptionPending` before attempting to use | ||
the returned value. | ||
## Name | ||
Names are JavaScript values that can be used as a property name. There are two | ||
specialized types of names supported in Node.js Addon API- [`String`](String.md) | ||
and [`Symbol`](Symbol.md). | ||
### Methods | ||
#### Constructor | ||
```cpp | ||
Name(); | ||
``` | ||
Returns an empty `Name`. | ||
```cpp | ||
Name(napi_env env, napi_value value); | ||
``` | ||
- `[in] env` - The environment in which to create the array. | ||
- `[in] value` - The primitive to wrap. | ||
Returns a Name created from the JavaScript primitive. | ||
Note: | ||
The value is not coerced to a string. | ||
## Array | ||
Arrays are native representations of JavaScript Arrays. `Napi::Array` is a wrapper | ||
around `napi_value` representing a JavaScript Array. | ||
### Constructor | ||
```cpp | ||
Array(); | ||
``` | ||
Returns an empty array. | ||
If an error occurs, a `Napi::Error` will be thrown. If C++ exceptions are not | ||
being used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. | ||
```cpp | ||
Array(napi_env env, napi_value value); | ||
``` | ||
- `[in] env` - The environment in which to create the array. | ||
- `[in] value` - The primitive to wrap. | ||
Returns a `Napi::Array` wrapping a `napi_value`. | ||
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not | ||
being used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. | ||
### Methods | ||
#### New | ||
```cpp | ||
static Array New(napi_env env); | ||
``` | ||
- `[in] env` - The environment in which to create the array. | ||
Returns a new `Napi::Array`. | ||
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not | ||
being used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. | ||
#### New | ||
```cpp | ||
static Array New(napi_env env, size_t length); | ||
``` | ||
- `[in] env` - The environment in which to create the array. | ||
- `[in] length` - The length of the array. | ||
Returns a new `Napi::Array` with the given length. | ||
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not | ||
being used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. | ||
#### New | ||
```cpp | ||
uint32_t Length() const; | ||
``` | ||
Returns the length of the array. | ||
Note: | ||
This can execute JavaScript code implicitly according to JavaScript semantics. | ||
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not | ||
being used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. |
# Buffer | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
The `Buffer` class creates a projection of raw data that can be consumed by | ||
script. | ||
## Methods | ||
### New | ||
Allocates a new `Buffer` object with a given length. | ||
```cpp | ||
static Buffer<T> New(napi_env env, size_t length); | ||
``` | ||
- `[in] env`: The environment in which to create the `Buffer` object. | ||
- `[in] length`: The number of `T` elements to allocate. | ||
Returns a new `Buffer` object. | ||
### New | ||
Wraps the provided external data into a new `Buffer` object. | ||
The `Buffer` object does not assume ownership for the data and expects it to be | ||
valid for the lifetime of the object. Since the `Buffer` is subject to garbage | ||
collection this overload is only suitable for data which is static and never | ||
needs to be freed. | ||
```cpp | ||
static Buffer<T> New(napi_env env, T* data, size_t length); | ||
``` | ||
- `[in] env`: The environment in which to create the `Buffer` object. | ||
- `[in] data`: The pointer to the external data to expose. | ||
- `[in] length`: The number of `T` elements in the external data. | ||
Returns a new `Buffer` object. | ||
### New | ||
Wraps the provided external data into a new `Buffer` object. | ||
The `Buffer` object does not assume ownership for the data and expects it | ||
to be valid for the lifetime of the object. The data can only be freed once the | ||
`finalizeCallback` is invoked to indicate that the `Buffer` has been released. | ||
```cpp | ||
template <typename Finalizer> | ||
static Buffer<T> New(napi_env env, | ||
T* data, | ||
size_t length, | ||
Finalizer finalizeCallback); | ||
``` | ||
- `[in] env`: The environment in which to create the `Buffer` object. | ||
- `[in] data`: The pointer to the external data to expose. | ||
- `[in] length`: The number of `T` elements in the external data. | ||
- `[in] finalizeCallback`: The function to be called when the `Buffer` is | ||
destroyed. It must implement `operator()`, accept a `T*` (which is the | ||
external data pointer), and return `void`. | ||
Returns a new `Buffer` object. | ||
### New | ||
Wraps the provided external data into a new `Buffer` object. | ||
The `Buffer` object does not assume ownership for the data and expects it to be | ||
valid for the lifetime of the object. The data can only be freed once the | ||
`finalizeCallback` is invoked to indicate that the `Buffer` has been released. | ||
```cpp | ||
template <typename Finalizer, typename Hint> | ||
static Buffer<T> New(napi_env env, | ||
T* data, | ||
size_t length, | ||
Finalizer finalizeCallback, | ||
Hint* finalizeHint); | ||
``` | ||
- `[in] env`: The environment in which to create the `Buffer` object. | ||
- `[in] data`: The pointer to the external data to expose. | ||
- `[in] length`: The number of `T` elements in the external data. | ||
- `[in] finalizeCallback`: The function to be called when the `Buffer` is | ||
destroyed. It must implement `operator()`, accept a `T*` (which is the | ||
external data pointer) and `Hint*`, and return `void`. | ||
- `[in] finalizeHint`: The hint to be passed as the second parameter of the | ||
finalize callback. | ||
Returns a new `Buffer` object. | ||
### Copy | ||
Allocates a new `Buffer` object and copies the provided external data into it. | ||
```cpp | ||
static Buffer<T> Copy(napi_env env, const T* data, size_t length); | ||
``` | ||
- `[in] env`: The environment in which to create the `Buffer` object. | ||
- `[in] data`: The pointer to the external data to copy. | ||
- `[in] length`: The number of `T` elements in the external data. | ||
Returns a new `Buffer` object containing a copy of the data. | ||
### Constructor | ||
Initializes an empty instance of the `Buffer` class. | ||
```cpp | ||
Buffer(); | ||
``` | ||
### Constructor | ||
Initializes the `Buffer` object using an existing Uint8Array. | ||
```cpp | ||
Buffer(napi_env env, napi_value value); | ||
``` | ||
- `[in] env`: The environment in which to create the `Buffer` object. | ||
- `[in] value`: The Uint8Array reference to wrap. | ||
### Data | ||
```cpp | ||
T* Data() const; | ||
``` | ||
Returns a pointer the external data. | ||
### Length | ||
```cpp | ||
size_t Length() const; | ||
``` | ||
Returns the number of `T` elements in the external data. |
@@ -55,3 +55,3 @@ **WORK IN PROGRESS, NOT YET COMPLETE** | ||
Returns the number of arguments passed in the Callabckinfo object. | ||
Returns the number of arguments passed in the CallbackInfo object. | ||
@@ -58,0 +58,0 @@ ### operator [] |
# Class propertry and descriptior | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
You are reading a draft of the next documentation and it's in continuous update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) |
@@ -19,4 +19,4 @@ # Creating a release | ||
to validate tests pass for latest 9, 8, 6, 4 releases | ||
(note there are still some issues on smartos and | ||
windows in the testing). | ||
(note there are still some issues on SmartOS and | ||
Windows in the testing). | ||
@@ -34,3 +34,3 @@ * Update the version in package.json appropriately. | ||
* Create a release in github (look at existing releases for an example). | ||
* Create a release in Github (look at existing releases for an example). | ||
@@ -37,0 +37,0 @@ * Validate that you can run `npm install node-addon-api` successfully |
# Error handling | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
Error handling represents one of the most important considerations when | ||
implementing a Node.js native add-on. When an error occurs in your C++ code you | ||
have to handle and dispatch it correctly. **node-addon-api** uses return values and | ||
JavaScript exceptions for error handling. You can choose return values or | ||
exception handling based on the mechanism that works best for your add-on. | ||
The **Error** is a persistent reference (for more info see: [Object reference](object_reference.md)) | ||
to a JavaScript error object. Use of this class depends on whether C++ | ||
exceptions are enabled at compile time. | ||
If C++ exceptions are enabled (for more info see: [Setup](setup.md)), then the | ||
**Error** class extends `std::exception` and enables integrated | ||
error-handling for C++ exceptions and JavaScript exceptions. | ||
The following sections explain the approach for each case: | ||
- [Handling Errors With C++ Exceptions](#exceptions) | ||
- [Handling Errors Without C++ Exceptions](#noexceptions) | ||
<a name="exceptions"></a> | ||
In most cases when an error occurs, the addon should do whatever clean is possible | ||
and then return to JavaScript so that they error can be propagated. In less frequent | ||
cases the addon may be able to recover from the error, clear the error and then | ||
continue. | ||
## Handling Errors With C++ Exceptions | ||
When C++ exceptions are enabled try/catch can be used to catch exceptions thrown | ||
from calls to JavaScript and then they can either be handled or rethrown before | ||
returning from a native method. | ||
If a node-addon-api call fails without executing any JavaScript code (for example due to | ||
an invalid argument), then node-addon-api automatically converts and throws | ||
the error as a C++ exception of type **Error**. | ||
If a JavaScript function called by C++ code via node-addon-api throws a JavaScript | ||
exception, then node-addon-api automatically converts and throws it as a C++ | ||
exception of type **Error** on return from the JavaScript code to the native | ||
method. | ||
If a C++ exception of type **Error** escapes from a N-API C++ callback, then | ||
the N-API wrapper automatically converts and throws it as a JavaScript exception. | ||
On return from a native method, node-addon-api will automatically convert a pending C++ | ||
exception to a JavaScript exception. | ||
When C++ exceptions are enabled try/catch can be used to catch exceptions thrown | ||
from calls to JavaScript and then they can either be handled or rethrown before | ||
returning from a native method. | ||
## Examples with C++ exceptions enabled | ||
### Throwing a C++ exception | ||
```cpp | ||
Env env = ... | ||
throw Error::New(env, "Example exception"); | ||
// other C++ statements | ||
// ... | ||
``` | ||
The statements following the throw statement will not be executed. The exception | ||
will bubble up as a C++ exception of type **Error**, until it is either caught | ||
while still in C++, or else automatically propagated as a JavaScript exception | ||
when returning to JavaScript. | ||
### Propagating a N-API C++ exception | ||
```cpp | ||
Function jsFunctionThatThrows = someObj.As<Function>(); | ||
Value result = jsFunctionThatThrows({ arg1, arg2 }); | ||
// other C++ statements | ||
// ... | ||
``` | ||
The C++ statements following the call to the JavaScript function will not be | ||
executed. The exception will bubble up as a C++ exception of type **Error**, | ||
until it is either caught while still in C++, or else automatically propagated as | ||
a JavaScript exception when returning to JavaScript. | ||
### Handling a N-API C++ exception | ||
```cpp | ||
Function jsFunctionThatThrows = someObj.As<Function>(); | ||
Value result; | ||
try { | ||
result = jsFunctionThatThrows({ arg1, arg2 }); | ||
} catch (const Error& e) { | ||
cerr << "Caught JavaScript exception: " + e.what(); | ||
} | ||
``` | ||
Since the exception was caught here, it will not be propagated as a JavaScript | ||
exception. | ||
<a name="noexceptions"></a> | ||
## Handling Errors Without C++ Exceptions | ||
If C++ exceptions are disabled (for more info see: [Setup](setup.md)), then the | ||
**Error** class does not extend `std::exception`. This means that any calls to | ||
node-addon-api function do not throw a C++ exceptions. Instead, it raises | ||
_pending_ JavaScript exceptions and returns an _empty_ **Value**. | ||
The calling code should check `env.IsExceptionPending()` before attempting to use a | ||
returned value, and may use methods on the **Env** class | ||
to check for, get, and clear a pending JavaScript exception (for more info see: [Env](env.md)). | ||
If the pending exception is not cleared, it will be thrown when the native code | ||
returns to JavaScript. | ||
## Examples with C++ exceptions disabled | ||
### Throwing a JS exception | ||
```cpp | ||
Env env = ... | ||
Error::New(env, "Example exception").ThrowAsJavaScriptException(); | ||
return; | ||
``` | ||
After throwing a JavaScript exception, the code should generally return | ||
immediately from the native callback, after performing any necessary cleanup. | ||
### Propagating a N-API JS exception | ||
```cpp | ||
Env env = ... | ||
Function jsFunctionThatThrows = someObj.As<Function>(); | ||
Value result = jsFunctionThatThrows({ arg1, arg2 }); | ||
if (env.IsExceptionPending()) { | ||
Error e = env.GetAndClearPendingException(); | ||
return e.Value(); | ||
} | ||
``` | ||
If env.IsExceptionPending() is returns true a | ||
JavaScript exception is pending. To let the exception propagate, the code should | ||
generally return immediately from the native callback, after performing any | ||
necessary cleanup. | ||
### Handling a N-API JS exception | ||
```cpp | ||
Env env = ... | ||
Function jsFunctionThatThrows = someObj.As<Function>(); | ||
Value result = jsFunctionThatThrows({ arg1, arg2 }); | ||
if (env.IsExceptionPending()) { | ||
Error e = env.GetAndClearPendingException(); | ||
cerr << "Caught JavaScript exception: " + e.Message(); | ||
} | ||
``` | ||
Since the exception was cleared here, it will not be propagated as a JavaScript | ||
exception after the native callback returns. |
116
doc/error.md
# Error | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
The **Error** class is a representation of the JavaScript Error object that is thrown | ||
when runtime errors occur. The Error object can also be used as a base object for | ||
user-defined exceptions. | ||
The **Error** class is a persistent reference to a JavaScript error object thus | ||
inherits its behavior from the `ObjectReference` class (for more info see: [ObjectReference](object_reference.md)). | ||
If C++ exceptions are enabled (for more info see: [Setup](setup.md)), then the | ||
**Error** class extends `std::exception` and enables integrated | ||
error-handling for C++ exceptions and JavaScript exceptions. | ||
For more details about error handling refer to the section titled [Error handling](error_handling.md). | ||
## Methods | ||
### New | ||
Creates empty instance of an `Error` object for the specified environment. | ||
```cpp | ||
Error::New(Napi:Env env); | ||
``` | ||
- `[in] Env`: The environment in which to construct the Error object. | ||
Returns an instance of `Error` object. | ||
### New | ||
Creates instance of an `Error` object. | ||
```cpp | ||
Error::New(Napi:Env env, const char* message); | ||
``` | ||
- `[in] Env`: The environment in which to construct the Error object. | ||
- `[in] message`: Null-terminated string to be used as the message for the Error. | ||
Returns instance of an `Error` object. | ||
### New | ||
Creates instance of an `Error` object | ||
```cpp | ||
Error::New(Napi:Env env, const std::string& message); | ||
``` | ||
- `[in] Env`: The environment in which to construct the `Error` object. | ||
- `[in] message`: Reference string to be used as the message for the `Error`. | ||
Returns instance of an `Error` object. | ||
### Fatal | ||
In case of an unrecoverable error in a native module, a fatal error can be thrown | ||
to immediately terminate the process. | ||
```cpp | ||
static NAPI_NO_RETURN void Fatal(const char* location, const char* message); | ||
``` | ||
The function call does not return, the process will be terminated. | ||
### Constructor | ||
Creates empty instance of an `Error`. | ||
```cpp | ||
Error(); | ||
``` | ||
Returns an instance of `Error` object. | ||
### Constructor | ||
Initializes an `Error` instance from an existing JavaScript error object. | ||
```cpp | ||
Error(napi_env env, napi_value value); | ||
``` | ||
- `[in] Env`: The environment in which to construct the Error object. | ||
- `[in] value`: The `Error` reference to wrap. | ||
Returns instance of an `Error` object. | ||
### Message | ||
```cpp | ||
std::string& Message() const NAPI_NOEXCEPT; | ||
``` | ||
Returns the reference to the string that represent the message of the error. | ||
### ThrowAsJavaScriptException | ||
Throw the error as JavaScript exception. | ||
```cpp | ||
void ThrowAsJavaScriptException() const; | ||
``` | ||
Throws the error as a JavaScript exception. | ||
### what | ||
```cpp | ||
const char* what() const NAPI_NOEXCEPT override; | ||
``` | ||
Returns a pointer to a null-terminated string that is used to identify the | ||
exception. This method can be used only if the exception mechanism is enabled. |
# Function reference | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
You are reading a draft of the next documentation and it's in continuous update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) |
# Function | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
You are reading a draft of the next documentation and it's in continuous update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) |
@@ -15,9 +15,9 @@ # HandleScope | ||
Creates a new handle scope. | ||
Creates a new handle scope on the stack. | ||
```cpp | ||
HandleScope HandleScope::New(Napi:Env env); | ||
HandleScope(Napi:Env env); | ||
``` | ||
- `[in] Env`: The environment in which to construct the HandleScope object. | ||
- `[in] env`: The environment in which to construct the HandleScope object. | ||
@@ -29,10 +29,10 @@ Returns a new HandleScope | ||
Creates a new handle scope. | ||
Creates a new handle scope on the stack. | ||
```cpp | ||
HandleScope HandleScope::New(napi_env env, napi_handle_scope scope); | ||
HandleScope(Napi::Env env, Napi::HandleScope scope); | ||
``` | ||
- `[in] env`: napi_env in which the scope passed in was created. | ||
- `[in] scope`: pre-existing napi_handle_scope. | ||
- `[in] env`: Napi::Env in which the scope passed in was created. | ||
- `[in] scope`: pre-existing Napi::HandleScope. | ||
@@ -46,3 +46,3 @@ Returns a new HandleScope instance which wraps the napi_handle_scope | ||
```cpp | ||
operator HandleScope::napi_handle_scope() const | ||
operator napi_handle_scope() const | ||
``` | ||
@@ -49,0 +49,0 @@ |
@@ -7,4 +7,4 @@ # node-gyp | ||
The main reason for this is that we need to link to the Node.js dependencies and | ||
headers correcrtly, another reason is that we need a cross platform way to build | ||
C++ soucre into binary for the target platform, | ||
headers correctly, another reason is that we need a cross platform way to build | ||
C++ source into binary for the target platform. | ||
@@ -11,0 +11,0 @@ Until now **node-gyp** is the **de-facto** standard build tool for writing |
@@ -38,3 +38,3 @@ # Object lifetime management | ||
Value newValue = String::New(info.Env(), name.c_str()); | ||
// do something with neValue | ||
// do something with newValue | ||
}; | ||
@@ -41,0 +41,0 @@ ``` |
@@ -1,5 +0,117 @@ | ||
# Object reference | ||
# Object Reference | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
ObjectReference is a subclass of [Reference](reference.md), and is equivalent to an instance of `Reference<Object>`. This means that an ObjectReference holds an [Object](object.md), and a count of the number of references to that Object. When the count is greater than 0, an ObjectReference is not eligible for garbage collection. This ensures that the Object being held as a value of the ObjectReference will remain accessible, even if the original Object no longer is. However, ObjectReference is unique from a Reference since properties can be set and get to the Object itself that can be accessed through the ObjectReference. | ||
For more general information on references, please consult [Reference](referenc.md). | ||
## Example | ||
```cpp | ||
#include <napi.h> | ||
using namescape Napi; | ||
void Init(Env env) { | ||
// Create an empty ObjectReference that has an initial reference count of 2. | ||
ObjectReference obj_ref = Reference<Object>::New(Object::New(env), 2); | ||
// Set a couple of different properties on the reference. | ||
obj_ref.Set("hello", String::New(env, "world")); | ||
obj_ref.Set(42, "The Answer to Life, the Universe, and Everything"); | ||
// Get the properties using the keys. | ||
Value val1 = obj_ref.Get("hello"); | ||
Value val2 = obj_ref.Get(42); | ||
} | ||
``` | ||
## Methods | ||
### Initialization | ||
```cpp | ||
static ObjectReference New(const Object& value, uint32_t initialRefcount = 0); | ||
``` | ||
* `[in] value`: The Object which is to be referenced. | ||
* `[in] initialRefcount`: The initial reference count. | ||
Returns the newly created reference. | ||
```cpp | ||
static ObjectReference Weak(const Object& value); | ||
``` | ||
Creates a "weak" reference to the value, in that the initial count of number of references is set to 0. | ||
* `[in] value`: The value which is to be referenced. | ||
Returns the newly created reference. | ||
```cpp | ||
static ObjectReference Persistent(const Object& value); | ||
``` | ||
Creates a "persistent" reference to the value, in that the initial count of number of references is set to 1. | ||
* `[in] value`: The value which is to be referenced. | ||
Returns the newly created reference. | ||
### Empty Constructor | ||
```cpp | ||
ObjectReference(); | ||
``` | ||
Returns a new _empty_ ObjectReference instance. | ||
### Constructor | ||
```cpp | ||
ObjectReference(napi_env env, napi_value value); | ||
``` | ||
* `[in] env`: The `napi_env` environment in which to construct the ObjectReference object. | ||
* `[in] value`: The N-API primitive value to be held by the ObjectReference. | ||
Returns the newly created reference. | ||
### Set | ||
```cpp | ||
void Set(___ key, ___ value); | ||
``` | ||
* `[in] key`: The name for the property being assigned. | ||
* `[in] value`: The value being assigned to the property. | ||
The `key` can be any of the following types: | ||
- `const char*` | ||
- `const std::string` | ||
- `uint32_t` | ||
The `value` can be any of the following types: | ||
- `napi_value` | ||
- `Napi::Value` | ||
- `const char*` | ||
- `bool` | ||
- `double` | ||
### Get | ||
```cpp | ||
Value Get(___ key); | ||
``` | ||
* `[in] key`: The name of the property to return the value for. | ||
Returns the [Value](value.md) associated with the key property. Returns NULL if no such key exists. | ||
The `key` can be any of the following types: | ||
- `const char*` | ||
- `const std::string` | ||
- `uint32_t` | ||
@@ -11,4 +11,4 @@ ## Object Wrap | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
You are reading a draft of the next documentation and it's in continuous update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) |
# Object | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
The Object class corresponds to a JavaScript object. It is extended by the following node-addon-api classes that you may use when working with more specific types: | ||
- [Value](value.md) and extends [Array](array.md) | ||
- [ArrayBuffer](array_buffer.md) | ||
- [Buffer<T>](buffer.md) | ||
- [Function](function.md) | ||
- [TypedArray](typed_array.md). | ||
This class provides a number of convenience methods, most of which are used to set or get properties on a JavaScript object. For example, Set() and Get(). | ||
## Example | ||
```cpp | ||
#include <napi.h> | ||
using namespace Napi; | ||
Void Init(Env env) { | ||
// Create a new instance | ||
Object obj = Object::New(env); | ||
// Assign values to properties | ||
obj.Set("hello", "world"); | ||
obj.Set(42, "The Answer to Life, the Universe, and Everything"); | ||
obj.Set("Douglas Adams", true); | ||
// Get properties | ||
Value val1 = obj.Get("hello"); | ||
Value val2 = obj.Get(42); | ||
Value val3 = obj.Get("Douglas Adams"); | ||
// Test if objects have properties. | ||
bool obj1 = obj.Has("hello"); // true | ||
bool obj2 = obj.Has("world"); // false | ||
} | ||
``` | ||
## Methods | ||
### Empty Constructor | ||
```cpp | ||
Napi::Object::Object(); | ||
``` | ||
Creates a new empty Object instance. | ||
### Constructor | ||
```cpp | ||
Napi::Object::Object(napi_env env, napi_value value); | ||
``` | ||
- `[in] env`: The `napi_env` environment in which to construct the Value object. | ||
- `[in] value`: The C++ primitive from which to instantiate the Value. `value` may be any of: | ||
- bool | ||
- Any integer type | ||
- Any floating point type | ||
- const char* (encoded using UTF-8, null-terminated) | ||
- const char16_t* (encoded using UTF-16-LE, null-terminated) | ||
- std::string (encoded using UTF-8) | ||
- std::u16string | ||
- napi::Value | ||
- napi_value | ||
Creates a non-empty Object instance. | ||
### New() | ||
```cpp | ||
Object Napi::Object::New(napi_env env); | ||
``` | ||
- `[in] env`: The `napi_env` environment in which to construct the Value object. | ||
Creates a new Object value. | ||
### Set() | ||
```cpp | ||
void Napi::Object::Set (____ key, ____ value); | ||
``` | ||
- `[in] key`: The name for the property being assigned. | ||
- `[in] value`: The value being assigned to the property. | ||
Add a property with the specified key with the specified value to the object. | ||
The key can be any of the following types: | ||
- `napi_value` | ||
- [Value](value.md) | ||
- `const char*` | ||
- `const std::string&` | ||
- `uint32_t` | ||
While the value must be any of the following types: | ||
- `napi_value` | ||
- [Value](value.md) | ||
- `const char*` | ||
- `std::string&` | ||
- `bool` | ||
- `double` | ||
### Get() | ||
```cpp | ||
Value Napi::Object::Get(____ key); | ||
``` | ||
- `[in] key`: The name of the property to return the value for. | ||
Returns the [Value](value.md) associated with the key property. Returns NULL if no such key exists. | ||
The `key` can be any of the following types: | ||
- `napi_value` | ||
- [Value](value.md) | ||
- `const char *` | ||
- `const std::string &` | ||
- `uint32_t` | ||
### Has() | ||
```cpp | ||
bool Napi::Object::Has (____ key) const; | ||
``` | ||
- `[in] key`: The name of the property to check. | ||
Returns a `bool` that is *true* if the object has a property named `key` and *false* otherwise. | ||
### InstanceOf() | ||
```cpp | ||
bool Napi::Object::InstanceOf (const Function& constructor) const | ||
``` | ||
- `[in] constructor`: The constructor [Function](function.md) of the value that is being compared with the object. | ||
Returns a `bool` that is true if the Object is an instance created by the `constructor` and false otherwise. | ||
Note: This is equivalent to the JavaScript instanceof operator. | ||
### DefineProperty() | ||
```cpp | ||
void Napi::Object::DefineProperty (const PropertyDescriptor& property); | ||
``` | ||
- `[in] property`: A [PropertyDescriptor](propertydescriptor.md). | ||
Define a property on the object. | ||
### DefineProperties() | ||
```cpp | ||
void Napi::Object::DefineProperties (____ properties) | ||
``` | ||
- `[in] properties`: A list of [PropertyDescriptor](propertydescriptor.md). Can be one of the following types: | ||
- const std::initializer_list<PropertyDescriptor>& | ||
- const std::vector<PropertyDescriptor>& | ||
Defines properties on the object. | ||
### Operator[]() | ||
```cpp | ||
PropertyLValue<std::string> Napi::Object::operator[] (const char* utf8name); | ||
``` | ||
- `[in] utf8name`: UTF-8 encoded null-terminated property name. | ||
Returns a [PropertyLValue](propertylvalue.md) as the named property or sets the named property. | ||
```cpp | ||
PropertyLValue<std::string> Napi::Object::operator[] (const std::string& utf8name); | ||
``` | ||
- `[in] utf8name`: UTF-8 encoded property name. | ||
Returns a [PropertyLValue](propertylvalue.md) as the named property or sets the named property. | ||
```cpp | ||
PropertyLValue<uint32_t> Napi::Object::operator[] (uint32_t index); | ||
``` | ||
- `[in] index`: Element index. | ||
Returns a [PropertyLValue](propertylvalue.md) or sets an indexed property or array element. | ||
```cpp | ||
Value Napi::Object::operator[] (const char* utf8name) const; | ||
``` | ||
- `[in] utf8name`: UTF-8 encoded null-terminated property name. | ||
Returns the named property as a [Value](value.md). | ||
```cpp | ||
Value Napi::Object::operator[] (const std::string& utf8name) const; | ||
``` | ||
- `[in] utf8name`: UTF-8 encoded property name. | ||
Returns the named property as a [Value](value.md). | ||
```cpp | ||
Value Napi::Object::operator[] (uint32_t index) const; | ||
``` | ||
- `[in] index`: Element index. | ||
Returns an indexed property or array element as a [Value](value.md). |
@@ -0,5 +1,70 @@ | ||
You are reading a draft of the next documentation and it's in continuous update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
# Promise | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
The Promise class, along with its Promise::Deferred class, implement the ability to create, resolve, and reject Promise objects. | ||
The basic approach is to create a Promise::Deferred object and return to your caller the value returned by the Promise::Deferred::Promise method. For example: | ||
```cpp | ||
Value YourFunction(const CallbackInfo& info) { | ||
// your code goes here... | ||
Promise::Deferred deferred = Promise::Deferred::New(info.Env()); | ||
// deferred needs to survive this call... | ||
return deferred.Promise(); | ||
} | ||
``` | ||
Later, when the asynchronous process completes, call either the `Resolve` or `Reject` method on the Promise::Deferred object created earlier: | ||
```cpp | ||
deferred.Resolve(String::New(info.Env(), "OK")); | ||
``` | ||
## Promise::Deferred Methods | ||
### Factory Method | ||
```cpp | ||
static Promise::Deferred Promise::Deferred::New(napi_env env); | ||
``` | ||
* `[in] env`: The `napi_env` environment in which to create the Deferred object. | ||
### Constructor | ||
```cpp | ||
Promise::Deferred(napi_env env); | ||
``` | ||
* `[in] env`: The `napi_env` environment in which to construct the Deferred object. | ||
### Promise | ||
```cpp | ||
Promise Promise::Deferred::Promise() const; | ||
``` | ||
Returns the Promise object held by the Promise::Deferred object. | ||
### Resolve | ||
```cpp | ||
void Promise::Deferred::Resolve(napi_value value) const; | ||
``` | ||
Resolves the Promise object held by the Promise::Deferred object. | ||
* `[in] value`: The N-API primitive value with which to resolve the Promise. | ||
### Reject | ||
```cpp | ||
void Promise::Deferred::Reject(napi_value value) const; | ||
``` | ||
Rejects the Promise object held by the Promise::Deferred object. | ||
* `[in] value`: The N-API primitive value with which to reject the Promise. |
@@ -1,5 +0,141 @@ | ||
# property descriptor | ||
# Property Descriptor | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
An [Object](object.md) can be assigned properites via its [DefineProperty](object.md#defineproperty) and [DefineProperties](object.md#defineproperties) function, which take PropertyDescrptor(s) as their parameters. The PropertyDescriptor can contain either values or functions, which are then assigned to the Object. Note that a single instance of a PropertyDescriptor class can only contain either one value, or at most two functions. PropertyDescriptors can only be created through the class methods [Accessor](#accessor), [Function](#function), or [Value](#value), each of which return a new static instance of a PropertyDescriptor. | ||
## Example | ||
```cpp | ||
#include <napi.h> | ||
using namespace Napi; | ||
Value TestGetter(const CallbackInfo& info) { | ||
return Boolean::New(info.Env(), testValue); | ||
} | ||
void TestSetter(const CallbackInfo& info) { | ||
testValue = info[0].As<Boolean>(); | ||
} | ||
Value TestFunction(const CallbackInfo& info) { | ||
return Boolean::New(info.Env(), true); | ||
} | ||
Void Init(Env env) { | ||
// Accessor | ||
PropertyDescriptor pd1 = PropertyDescriptor::Accessor("pd1", TestGetter); | ||
PropertyDescriptor pd2 = PropertyDescriptor::Accessor("pd2", TestGetter, TestSetter); | ||
// Function | ||
PropertyDescriptor pd3 = PropertyDescriptor::Function("function", TestFunction); | ||
// Value | ||
Boolean true_bool = Boolean::New(env, true); | ||
PropertyDescriptor pd4 = PropertyDescriptor::Value("boolean value", TestFunction, napi_writable); | ||
// Assign to an Object | ||
Object obj = Object::New(env); | ||
obj.DefineProperties({pd1, pd2, pd3, pd4}); | ||
} | ||
``` | ||
## Methods | ||
### Constructor | ||
```cpp | ||
Napi::PropertyDescriptor::PropertyDescriptor (napi_property_descriptor desc); | ||
``` | ||
* `[in] desc`: A PropertyDescriptor that is needed in order to create another PropertyDescriptor. | ||
### Accessor | ||
```cpp | ||
static PropertyDescriptor Napi::PropertyDescriptor::Accessor (___ name, | ||
Getter getter, | ||
napi_property_attributes attributes = napi_default, | ||
void *data = nullptr); | ||
``` | ||
* `[in] name`: The name used for the getter function. | ||
* `[in] getter`: A getter function. | ||
* `[in] attributes`: Potential attributes for the getter function. | ||
* `[in] data`: A pointer to data of any type, default is a null pointer. | ||
Returns a PropertyDescriptor that contains a function. | ||
The name of the property can be any of the following types: | ||
- `const char*` | ||
- `const std::string &` | ||
- `napi_value value` | ||
- `Name` | ||
```cpp | ||
static PropertyDescriptor Napi::PropertyDescriptor::Accessor (___ name, | ||
Getter getter, | ||
Setter setter, | ||
napi_property_attributes attributes = napi_default, | ||
void *data = nullptr); | ||
``` | ||
* `[in] name`: The name of the getter and setter function. | ||
* `[in] getter`: The getter function. | ||
* `[in] setter`: The setter function. | ||
* `[in] attributes`: Potential attributes for the getter function. | ||
* `[in] data`: A pointer to data of any type, default is a null pointer. | ||
Returns a PropertyDescriptor that contains a Getter and Setter function. | ||
The name of the property can be any of the following types: | ||
- `const char*` | ||
- `const std::string &` | ||
- `napi_value value` | ||
- `Name` | ||
### Function | ||
```cpp | ||
static PropertyDescriptor Napi::PropertyDescriptor::Function (___ name, | ||
Callable cb, | ||
napi_property_attributes attributes = napi_default, | ||
void *data = nullptr); | ||
``` | ||
* `[in] name`: The name of the Callable function. | ||
* `[in] cb`: The function | ||
* `[in] attributes`: Potential attributes for the getter function. | ||
* `[in] data`: A pointer to data of any type, default is a null pointer. | ||
Returns a PropertyDescriptor that contains a callable Function. | ||
The name of the property can be any of the following types: | ||
- `const char*` | ||
- `const std::string &` | ||
- `napi_value value` | ||
- `Name` | ||
### Value | ||
```cpp | ||
static PropertyDescriptor Napi::PropertyDescriptor::Value (___ name, | ||
napi_value value, | ||
napi_property_attributes attributes = napi_default); | ||
``` | ||
The name of the property can be any of the following types: | ||
- `const char*` | ||
- `const std::string &` | ||
- `napi_value value` | ||
- `Name` | ||
## Related Information | ||
### napi\_property\_attributes | ||
`napi_property_attributes` are flags used to indicate to JavaScript certain permissions that the property is meant to have. The following are the flag options: | ||
- napi\_default, | ||
- napi\_writable, | ||
- napi\_enumerable, | ||
- napi\_configurable | ||
For more information on the flags and on napi\_property\_attributes, please read the documentation [here](https://github.com/nodejs/node/blob/master/doc/api/n-api.md#napi_property_attributes). | ||
@@ -1,5 +0,115 @@ | ||
# Reference | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
# Reference (template) | ||
Holds a counted reference to a [Value](value.md) object; initially a weak reference unless otherwise specified, may be changed to/from a strong reference by adjusting the refcount. | ||
The referenced Value is not immediately destroyed when the reference count is zero; it is merely then eligible for garbage-collection if there are no other references to the Value. | ||
Reference objects allocated in static space, such as a global static instance, must call the `SuppressDestruct` method to prevent its destructor, running at program shutdown time, from attempting to reset the reference when the environment is no longer valid. | ||
The following classes inherit, either directly or indirectly, from Reference: | ||
* [ObjectWrap](object_wrap.md) | ||
* [ObjectReference](object_reference.md) | ||
* [FunctionReference](function_reference.md) | ||
## Methods | ||
### Factory Method | ||
```cpp | ||
static Reference<T> New(const T& value, uint32_t initialRefcount = 0); | ||
``` | ||
* `[in] value`: The value which is to be referenced. | ||
* `[in] initialRefcount`: The initial reference count. | ||
### Empty Constructor | ||
```cpp | ||
Reference(); | ||
``` | ||
Creates a new _empty_ Reference instance. | ||
### Constructor | ||
```cpp | ||
Reference(napi_env env, napi_value value); | ||
``` | ||
* `[in] env`: The `napi_env` environment in which to construct the Reference object. | ||
* `[in] value`: The N-API primitive value to be held by the Reference. | ||
### Env | ||
```cpp | ||
Napi::Env Env() const; | ||
``` | ||
Returns the `Env` value in which the Reference was instantiated. | ||
### IsEmpty | ||
```cpp | ||
bool IsEmpty() const; | ||
``` | ||
Determines whether the value held by the Reference is empty. | ||
### Value | ||
```cpp | ||
T Value() const; | ||
``` | ||
Returns the value held by the Reference. | ||
### Ref | ||
```cpp | ||
uint32_t Ref(); | ||
``` | ||
Increments the reference count for the Reference and returns the resulting reference count. Throws an error if the increment fails. | ||
### Unref | ||
```cpp | ||
uint32_t Unref(); | ||
``` | ||
Decrements the reference count for the Reference and returns the resulting reference count. Throws an error if the decrement fails. | ||
### Reset (Empty) | ||
```cpp | ||
void Reset(); | ||
``` | ||
Sets the value held by the Reference to be empty. | ||
### Reset | ||
```cpp | ||
void Reset(const T& value, uint32_t refcount = 0); | ||
``` | ||
* `[in] value`: The value which is to be referenced. | ||
* `[in] initialRefcount`: The initial reference count. | ||
Sets the value held by the Reference. | ||
### SuppressDestruct | ||
```cpp | ||
void SuppressDestruct(); | ||
``` | ||
Call this method on a Reference that is declared as static data to prevent its destructor, running at program shutdown time, from attempting to reset the reference when the environment is no longer valid. |
@@ -22,3 +22,3 @@ # Setup | ||
"dependencies": { | ||
"node-addon-api": "1.1.0", | ||
"node-addon-api": "1.2.0", | ||
} | ||
@@ -25,0 +25,0 @@ ``` |
# String | ||
You are reading a draft of the next documentation and it's in continuous update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
# Methods | ||
## Constructor | ||
### Constructor | ||
Creates a new String value from a UTF-8 encoded c++ string. | ||
```cpp | ||
String::New(napi_env env, const std::string& value); | ||
String(); | ||
``` | ||
- `[in] env`: The `napi_env` environment in which to construct the Value object. | ||
- `[in] value`: The C++ primitive from which to instantiate the Value. `value` may be any of: | ||
- std::string& | ||
- std::u16string& | ||
- const char* | ||
- const char16_t* | ||
Returns a new **empty** String instance. | ||
Creates a new empty String | ||
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not | ||
being used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. | ||
```cpp | ||
String::New(); | ||
``` | ||
String(napi_env env, napi_value value); ///< Wraps a N-API value primitive. | ||
``` | ||
- `[in] env` - The environment in which to create the string. | ||
- `[in] value` - The primitive to wrap. | ||
Returns a `Napi::String` wrapping a `napi_value`. | ||
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not | ||
being used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. | ||
## Operators | ||
### operator std::string | ||
@@ -34,4 +34,5 @@ | ||
``` | ||
Converts a String value to a UTF-8 encoded C++ string. | ||
Returns a UTF-8 encoded C++ string. | ||
### operator std::u16string | ||
@@ -41,4 +42,35 @@ ```cpp | ||
``` | ||
Converts a String value to a UTF-16 encoded C++ string. | ||
Returns a UTF-16 encoded C++ string. | ||
## Methods | ||
### New | ||
```cpp | ||
String::New(); | ||
``` | ||
Returns a new empty String | ||
### New | ||
```cpp | ||
String::New(napi_env env, const std::string& value); | ||
String::New(napi_env env, const std::u16string& value); | ||
String::New(napi_env env, const char* value); | ||
String::New(napi_env env, const char16_t* value); | ||
``` | ||
- `[in] env`: The `napi_env` environment in which to construct the Value object. | ||
- `[in] value`: The C++ primitive from which to instantiate the Value. `value` may be any of: | ||
- `std::string&` - represents an ANSI string. | ||
- `std::u16string&` - represents a UTF16-LE string. | ||
- `const char*` - represents a UTF8 string. | ||
- `const char16_t*` - represents a UTF16-LE string. | ||
Returns a new `Napi::String` that represents the passed in C++ string. | ||
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not | ||
being used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. | ||
### Utf8Value | ||
@@ -48,3 +80,5 @@ ```cpp | ||
``` | ||
Converts a String value to a UTF-8 encoded C++ string. | ||
Returns a UTF-8 encoded C++ string. | ||
### Utf16Value | ||
@@ -54,2 +88,3 @@ ```cpp | ||
``` | ||
Converts a String value to a UTF-16 encoded C++ string. | ||
Returns a UTF-16 encoded C++ string. |
# Symbol | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
## Methods | ||
### Constructor | ||
Instantiates a new `Symbol` value | ||
```cpp | ||
Symbol(); | ||
``` | ||
Returns a new empty Symbol. | ||
### New | ||
```cpp | ||
Symbol::New(napi_env env, const std::string& description); | ||
Symbol::New(napi_env env, const char* description); | ||
Symbol::New(napi_env env, String description); | ||
Symbol::New(napi_env env, napi_value description); | ||
``` | ||
- `[in] env`: The `napi_env` environment in which to construct the Symbol object. | ||
- `[in] value`: The C++ primitive which represents the description hint for the Symbol. | ||
`description` may be any of: | ||
- `std::string&` - ANSI string description. | ||
- `const char*` - represents a UTF8 string description. | ||
- `String` - Node addon API String description. | ||
- `napi_value` - N-API `napi_value` description. | ||
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not | ||
being used, callers should check the result of `Env::IsExceptionPending` before | ||
attempting to use the returned value. | ||
### Utf8Value | ||
```cpp | ||
static Symbol WellKnown(napi_env env, const std::string& name); | ||
``` | ||
- `[in] env`: The `napi_env` environment in which to construct the Symbol object. | ||
- `[in] name`: The C++ string representing the `Symbol` to retrieve. | ||
Returns a `Napi::Symbol` representing a well-known Symbol from the | ||
Symbol registry. |
@@ -1,5 +0,133 @@ | ||
# Typed array of | ||
# TypedArrayOf | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
The `TypedArrayOf` class corresponds to the various | ||
[JavaScript `TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | ||
classes. | ||
## Typedefs | ||
The common JavaScript `TypedArray` types are pre-defined for each of use: | ||
```cpp | ||
typedef TypedArrayOf<int8_t> Int8Array; | ||
typedef TypedArrayOf<uint8_t> Uint8Array; | ||
typedef TypedArrayOf<int16_t> Int16Array; | ||
typedef TypedArrayOf<uint16_t> Uint16Array; | ||
typedef TypedArrayOf<int32_t> Int32Array; | ||
typedef TypedArrayOf<uint32_t> Uint32Array; | ||
typedef TypedArrayOf<float> Float32Array; | ||
typedef TypedArrayOf<double> Float64Array; | ||
``` | ||
The one exception is the `Uint8ClampedArray` which requires explicit | ||
initialization: | ||
```cpp | ||
Uint8Array::New(env, length, napi_uint8_clamped_array) | ||
``` | ||
Note that while it's possible to create a "clamped" array the _clamping_ | ||
behavior is only applied in JavaScript. | ||
## Methods | ||
### New | ||
Allocates a new `TypedArray` instance with a given length. The underlying | ||
`ArrayBuffer` is allocated automatically to the desired number of elements. | ||
The array type parameter can normally be omitted (because it is inferred from | ||
the template parameter T), except when creating a "clamped" array. | ||
```cpp | ||
static TypedArrayOf New(napi_env env, | ||
size_t elementLength, | ||
napi_typedarray_type type); | ||
``` | ||
- `[in] env`: The environment in which to create the `TypedArrayOf` instance. | ||
- `[in] elementLength`: The length to be allocated, in elements. | ||
- `[in] type`: The type of array to allocate (optional). | ||
Returns a new `TypedArrayOf` instance. | ||
### New | ||
Wraps the provided `ArrayBuffer` into a new `TypedArray` instance. | ||
The array `type` parameter can normally be omitted (because it is inferred from | ||
the template parameter `T`), except when creating a "clamped" array. | ||
```cpp | ||
static TypedArrayOf New(napi_env env, | ||
size_t elementLength, | ||
Napi::ArrayBuffer arrayBuffer, | ||
size_t bufferOffset, | ||
napi_typedarray_type type); | ||
``` | ||
- `[in] env`: The environment in which to create the `TypedArrayOf` instance. | ||
- `[in] elementLength`: The length to array, in elements. | ||
- `[in] arrayBuffer`: The backing `ArrayBuffer` instance. | ||
- `[in] bufferOffset`: The offset into the `ArrayBuffer` where the array starts, | ||
in bytes. | ||
- `[in] type`: The type of array to allocate (optional). | ||
Returns a new `TypedArrayOf` instance. | ||
### Constructor | ||
Initializes an empty instance of the `TypedArrayOf` class. | ||
```cpp | ||
TypedArrayOf(); | ||
``` | ||
### Constructor | ||
Initializes a wrapper instance of an existing `TypedArrayOf` object. | ||
```cpp | ||
TypedArrayOf(napi_env env, napi_value value); | ||
``` | ||
- `[in] env`: The environment in which to create the `TypedArrayOf` object. | ||
- `[in] value`: The `TypedArrayOf` reference to wrap. | ||
### operator [] | ||
```cpp | ||
T& operator [](size_t index); | ||
``` | ||
- `[in] index: The element index into the array. | ||
Returns the element found at the given index. | ||
### operator [] | ||
```cpp | ||
const T& operator [](size_t index) const; | ||
``` | ||
- `[in] index: The element index into the array. | ||
Returns the element found at the given index. | ||
### Data | ||
```cpp | ||
T* Data() const; | ||
``` | ||
Returns a pointer into the backing `ArrayBuffer` which is offset to point to the | ||
start of the array. | ||
### Data | ||
```cpp | ||
const T* Data() const | ||
``` | ||
Returns a pointer into the backing `ArrayBuffer` which is offset to point to the | ||
start of the array. |
@@ -1,5 +0,74 @@ | ||
# Typed array | ||
# TypedArray | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
The `TypedArray` class corresponds to the | ||
[JavaScript `TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | ||
class. | ||
## Methods | ||
### Constructor | ||
Initializes an empty instance of the `TypedArray` class. | ||
```cpp | ||
TypedArray(); | ||
``` | ||
### Constructor | ||
Initializes a wrapper instance of an existing `TypedArray` instance. | ||
```cpp | ||
TypedArray(napi_env env, napi_value value); | ||
``` | ||
- `[in] env`: The environment in which to create the `TypedArray` instance. | ||
- `[in] value`: The `TypedArray` reference to wrap. | ||
### TypedArrayType | ||
```cpp | ||
napi_typedarray_type TypedArrayType() const; | ||
``` | ||
Returns the type of this instance. | ||
### ArrayBuffer | ||
```cpp | ||
Napi::ArrayBuffer ArrayBuffer() const; | ||
``` | ||
Returns the backing array buffer. | ||
### ElementSize | ||
```cpp | ||
uint8_t ElementSize() const; | ||
``` | ||
Returns the size of one element, in bytes. | ||
### ElementLength | ||
```cpp | ||
size_t ElementLength() const; | ||
``` | ||
Returns the number of elements. | ||
### ByteOffset | ||
```cpp | ||
size_t ByteOffset() const; | ||
``` | ||
Returns the offset into the `ArrayBuffer` where the array starts, in bytes. | ||
### ByteLength | ||
```cpp | ||
size_t ByteLength() const; | ||
``` | ||
Returns the length of the array, in bytes. |
@@ -7,3 +7,3 @@ **WORK IN PROGRESS, NOT YET COMPLETE** | ||
Value is a the base class upon which other JavaScipt values such as Number, Boolean, String, and Object are based. | ||
Value is a the base class upon which other JavaScript values such as Number, Boolean, String, and Object are based. | ||
@@ -10,0 +10,0 @@ The following classes inherit, either directly or indirectly, from Value: |
# Working with JavaScript Values | ||
You are reading a draft of the next documentation and it's in continuos update so | ||
You are reading a draft of the next documentation and it's in continuous update so | ||
if you don't find what you need please refer to: | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) | ||
[C++ wrapper classes for the ABI-stable C APIs for Node.js](https://nodejs.github.io/node-addon-api/) |
@@ -10,4 +10,5 @@ { | ||
"Arunesh Chandra (https://github.com/aruneshchandra)", | ||
"Ben Berman (https://github.com/rivertam)", | ||
"Benjamin Byholm (https://github.com/kkoopa)", | ||
"Cory Mickelson (https://github.com/corymickelson)", | ||
"Cory Mickelson (https://github.com/corymickelson)", | ||
"David Halls (https://github.com/davedoesdev)", | ||
@@ -20,2 +21,3 @@ "Eric Bickle (https://github.com/ebickle)", | ||
"Jinho Bang (https://github.com/romandev)", | ||
"joshgarde (https://github.com/joshgarde)", | ||
"Konstantin Tarkus (https://github.com/koistya)", | ||
@@ -27,2 +29,3 @@ "Kyle Farnung (https://github.com/kfarnung)", | ||
"Nicola Del Gobbo (https://github.com/NickNaso)", | ||
"Nick Soggin (https://github.com/iSkore)", | ||
"Rolf Timmermans (https://github.com/rolftimmermans)", | ||
@@ -53,3 +56,3 @@ "Sampson Gao (https://github.com/sampsongao)", | ||
}, | ||
"version": "1.3.0" | ||
"version": "1.4.0" | ||
} |
@@ -1,23 +0,31 @@ | ||
# **Node.js API (N-API) Package** | ||
# **node-addon-api module** | ||
This module contains **header-only C++ wrapper classes** which simplify | ||
the use of the C based [N-API](https://nodejs.org/dist/latest/docs/api/n-api.html) | ||
provided by Node.js when using C++. It provides a C++ object model | ||
and exception handling semantics with low overhead. | ||
This package contains **header-only C++ wrapper classes** for the | ||
**ABI-stable Node.js API** also known as **N-API**, providing C++ object | ||
model and exception handling semantics with low overhead. It guarantees | ||
backward compatibility when used with older versions of Node.js that do | ||
not have N-API built-in. | ||
N-API is an API for building native addons. It is independent from the | ||
underlying JavaScript runtime (e.g. V8 or ChakraCore) and is maintained as | ||
part of Node.js itself. This API will be Application Binary Interface (ABI) | ||
stable across versions and flavors of Node.js. It is intended to insulate | ||
N-API is an ABI stable C interface provided by Node.js for building native | ||
addons. It is independent from the underlying JavaScript runtime (e.g. V8 or ChakraCore) | ||
and is maintained as part of Node.js itself. It is intended to insulate | ||
native addons from changes in the underlying JavaScript engine and allow | ||
modules compiled for one version to run on later versions of Node.js without | ||
recompilation. N-API guarantees the **API** and **ABI** compatibility across | ||
different versions of Node.js. So if you switched to a different version of | ||
Node.js, you would not need to reinstall or recompile the native addon. | ||
recompilation. | ||
APIs exposed by N-API are generally used to create and manipulate JavaScript | ||
values. Concepts and operations generally map to ideas specified in the | ||
**ECMA262 Language Specification**. | ||
The `node-addon-api` module, which is not part of Node.js, preserves the benefits | ||
of the N-API as it consists only of inline code that depends only on the stable API | ||
provided by N-API. As such, modules built against one version of Node.js | ||
using node-addon-api should run without having to be rebuilt with newer versions | ||
of Node.js. | ||
As new APIs are added to N-API, node-addon-api must be updated to provide | ||
wrappers for those new APIs. For this reason node-addon-api provides | ||
methods that allow callers to obtain the underlying N-API handles so | ||
direct calls to N-API and the use of the objects/methods provided by | ||
node-addon-api can be used together. For example, in order to be able | ||
to use an API for which the node-add-api does not yet provide a wrapper. | ||
APIs exposed by node-addon-api are generally used to create and | ||
manipulate JavaScript values. Concepts and operations generally map | ||
to ideas specified in the **ECMA262 Language Specification**. | ||
- **[Setup](#setup)** | ||
@@ -32,3 +40,3 @@ - **[API Documentation](#api)** | ||
## **Current version: 1.3** | ||
## **Current version: 1.4** | ||
@@ -51,7 +59,11 @@ (See [CHANGELOG.md](CHANGELOG.md) for complete Changelog) | ||
### **API Documentation** | ||
The following is the documentation for node-addon-api (NOTE: | ||
still a work in progress as its not yet complete). | ||
- [Basic Types](doc/basic_types.md) | ||
- [Array](doc/array.md) | ||
- [Array](doc/basic_types.md#array) | ||
- [Symbol](doc/symbol.md) | ||
- [String](doc/string.md) | ||
- [Name](doc/name.md) | ||
- [Name](doc/basic_types.md#name) | ||
- [Number](doc/number.md) | ||
@@ -69,2 +81,4 @@ - [Boolean](doc/boolean.md) | ||
- [Error](doc/error.md) | ||
- [TypeError](doc/type_error.md) | ||
- [RangeError](doc/range_error.md) | ||
- [Object Lifetime Management](doc/object_lifetime_management.md) | ||
@@ -82,4 +96,5 @@ - [HandleScope](doc/handle_scope.md) | ||
- [TypedArrayOf](doc/typed_array_of.md) | ||
- [Memory Management](doc/memory_management.md) | ||
- [Async Operations](doc/async_operations.md) | ||
- [AsyncWorker](async_worker.md) | ||
- [AsyncWorker](doc/async_worker.md) | ||
- [Promises](doc/promises.md) | ||
@@ -91,3 +106,3 @@ | ||
Are you new to **N-API**? Take a look at our **[examples](https://github.com/nodejs/abi-stable-node-addon-examples)** | ||
Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/abi-stable-node-addon-examples)** | ||
@@ -98,3 +113,3 @@ - **[Hello World](https://github.com/nodejs/abi-stable-node-addon-examples/tree/master/1_hello_world/node-addon-api)** | ||
- **[Object factory](https://github.com/nodejs/abi-stable-node-addon-examples/tree/master/4_object_factory/node-addon-api)** | ||
- **[Function factory](https://github.com/nodejs/abi-stable-node-addon-examples/tree/master/4_object_factory/node-addon-api)** | ||
- **[Function factory](https://github.com/nodejs/abi-stable-node-addon-examples/tree/master/5_function_factory/node-addon-api)** | ||
- **[Wrapping C++ Object](https://github.com/nodejs/abi-stable-node-addon-examples/tree/master/6_object_wrap/node-addon-api)** | ||
@@ -108,3 +123,3 @@ - **[Factory of wrapped object](https://github.com/nodejs/abi-stable-node-addon-examples/tree/master/7_factory_wrap/node-addon-api)** | ||
To run the **N-API** tests do: | ||
To run the **node-addon-api** tests do: | ||
@@ -111,0 +126,0 @@ ``` |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
575688
62
152
1