### Install and Run Tests Source: https://github.com/nodejs/node-addon-api/blob/main/CONTRIBUTING.md Installs project dependencies and runs the test suite. ```bash npm install npm test ``` -------------------------------- ### Install node-addon-api Source: https://github.com/nodejs/node-addon-api/blob/main/doc/conversion-tool.md Install the node-addon-api module using npm. This is a prerequisite for running the conversion script. ```bash npm install node-addon-api ``` -------------------------------- ### C++ Example of Object Wrapping Source: https://github.com/nodejs/node-addon-api/blob/main/doc/object_wrap.md This C++ code defines a class 'Example' that inherits from Napi::ObjectWrap. It demonstrates how to initialize the class, define instance methods (GetValue, SetValue), static methods (CreateNewItem), and manage the constructor reference. ```cpp #include class Example : public Napi::ObjectWrap { public: static Napi::Object Init(Napi::Env env, Napi::Object exports); Example(const Napi::CallbackInfo& info); static Napi::Value CreateNewItem(const Napi::CallbackInfo& info); private: double _value; Napi::Value GetValue(const Napi::CallbackInfo& info); Napi::Value SetValue(const Napi::CallbackInfo& info); }; Napi::Object Example::Init(Napi::Env env, Napi::Object exports) { // This method is used to hook the accessor and method callbacks Napi::Function func = DefineClass(env, "Example", { InstanceMethod<&Example::GetValue>("GetValue", static_cast(napi_writable | napi_configurable)), InstanceMethod<&Example::SetValue>("SetValue", static_cast(napi_writable | napi_configurable)), StaticMethod<&Example::CreateNewItem>("CreateNewItem", static_cast(napi_writable | napi_configurable)), }); Napi::FunctionReference* constructor = new Napi::FunctionReference(); // Create a persistent reference to the class constructor. This will allow // a function called on a class prototype and a function // called on instance of a class to be distinguished from each other. *constructor = Napi::Persistent(func); exports.Set("Example", func); // Store the constructor as the add-on instance data. This will allow this // add-on to support multiple instances of itself running on multiple worker // threads, as well as multiple instances of itself running in different // contexts on the same thread. // // By default, the value set on the environment here will be destroyed when // the add-on is unloaded using the `delete` operator, but it is also // possible to supply a custom deleter. env.SetInstanceData(constructor); return exports; } Example::Example(const Napi::CallbackInfo& info) : Napi::ObjectWrap(info) { Napi::Env env = info.Env(); // ... Napi::Number value = info[0].As(); this->_value = value.DoubleValue(); } Napi::Value Example::GetValue(const Napi::CallbackInfo& info){ Napi::Env env = info.Env(); return Napi::Number::New(env, this->_value); } Napi::Value Example::SetValue(const Napi::CallbackInfo& info){ Napi::Env env = info.Env(); // ... Napi::Number value = info[0].As(); this->_value = value.DoubleValue(); return this->GetValue(info); } // Initialize native add-on Napi::Object Init (Napi::Env env, Napi::Object exports) { Example::Init(env, exports); return exports; } // Create a new item using the constructor stored during Init. Napi::Value Example::CreateNewItem(const Napi::CallbackInfo& info) { // Retrieve the instance data we stored during `Init()`. We only stored the // constructor there, so we retrieve it here to create a new instance of the // JS class the constructor represents. Napi::FunctionReference* constructor = info.Env().GetInstanceData(); return constructor->New({ Napi::Number::New(info.Env(), 42) }); } // Register and initialize native add-on NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) ``` -------------------------------- ### Install CMake.js Globally Source: https://github.com/nodejs/node-addon-api/blob/main/doc/cmake-js.md Install CMake.js as a global package for developer use. This command also shows how to access the help information. ```bash npm install -g cmake-js cmake-js --help ``` -------------------------------- ### JavaScript Usage of Napi::ClassPropertyDescriptor Example Source: https://github.com/nodejs/node-addon-api/blob/main/doc/class_property_descriptor.md This JavaScript code shows how to use the 'Example' class defined in C++ using Napi::ClassPropertyDescriptor. It demonstrates creating an instance, accessing a mutable property, and attempting to set a read-only property. ```javascript 'use strict'; const { Example } = require('bindings')('addon'); const example = new Example(11); console.log(example.value); // It prints 11 example.value = 19; console.log(example.value); // It prints 19 example.readOnlyProp = 500; console.log(example.readOnlyProp); // Unchanged. It prints 19 ``` -------------------------------- ### MaybeUnwrapTo Usage Example Source: https://github.com/nodejs/node-addon-api/blob/main/test/README.md Example demonstrating MaybeUnwrapTo to check for a property and suppress potential exceptions during the check. ```cpp Object opts = info[0].As(); bool hasProperty = false; // The check may throw, but we are going to suppress that. if (MaybeUnwrapTo(opts.Has("blocking"), &hasProperty)) { isBlocking = hasProperty && MaybeUnwrap(MaybeUnwrap(opts.Get("blocking")).ToBoolean()); } else { env.GetAndClearPendingException(); } ``` -------------------------------- ### Registering and Queuing AsyncProgressWorker Source: https://github.com/nodejs/node-addon-api/blob/main/doc/async_worker_variants.md Example of how to create, queue, and register an Napi::AsyncProgressWorker from C++. ```cpp #include // Include EchoWorker class // .. using namespace Napi; Value Echo(const CallbackInfo& info) { // We need to validate the arguments here std::string in = info[0].As(); Function cb = info[1].As(); EchoWorker* wk = new EchoWorker(cb, in); wk->Queue(); return info.Env().Undefined(); } // Register the native method for JS to access Object Init(Env env, Object exports) { exports.Set(String::New(env, "echo"), Function::New(env, Echo)); return exports; } // Register our native addon NODE_API_MODULE(nativeAddon, Init) ``` -------------------------------- ### JavaScript Usage of Wrapped C++ Object Source: https://github.com/nodejs/node-addon-api/blob/main/doc/object_wrap.md This JavaScript code demonstrates how to require and instantiate the C++ 'Example' class wrapped with Node-API. It shows calling instance methods to get and set a value. ```javascript 'use strict' const { Example } = require('bindings')('addon') const example = new Example(11) console.log(example.GetValue()) // It prints 11 example.SetValue(19) console.log(example.GetValue()); // It prints 19 ``` -------------------------------- ### MaybeUnwrap Usage Example Source: https://github.com/nodejs/node-addon-api/blob/main/test/README.md Example demonstrating the usage of MaybeUnwrap to retrieve a value from an object property, assuming no exceptions will be thrown. ```cpp Object obj = info[0].As(); // we are sure the parameters should not throw Value value = MaybeUnwrap(obj->Get("foobar")); ``` -------------------------------- ### MaybeUnwrapOr Usage Example Source: https://github.com/nodejs/node-addon-api/blob/main/test/README.md Example of using MaybeUnwrapOr to call a function with arguments and return its result, regardless of whether it throws an exception. ```cpp Value CallWithArgs(const CallbackInfo& info) { Function func = info[0].As(); // We don't care if the operation is throwing or not, just return it back to node-addon-api return MaybeUnwrapOr( func.Call(std::initializer_list{info[1], info[2], info[3]})); } ``` -------------------------------- ### Napi::Number Casting Example Source: https://github.com/nodejs/node-addon-api/blob/main/doc/number.md Example demonstrating casting a Napi::Number to an unsigned 32-bit integer. ```APIDOC ## Example The following shows an example of casting a number to an `uint32_t` value. ```cpp uint32_t operatorVal = Napi::Number::New(Env(), 10.0); // Number to unsigned 32 bit integer // or auto instanceVal = info[0].As().Uint32Value(); ``` ``` -------------------------------- ### Define Example Addon with Instance Methods Source: https://github.com/nodejs/node-addon-api/blob/main/doc/addon.md This C++ code defines a native add-on class 'ExampleAddon' that inherits from Napi::Addon. It demonstrates how to declare instance methods like 'Increment' and 'Decrement', and how to attach them to the exports object, including nested objects. ```cpp #include class ExampleAddon : public Napi::Addon { public: ExampleAddon(Napi::Env env, Napi::Object exports) { // In the constructor we declare the functions the add-on makes available // to JavaScript. DefineAddon(exports, { InstanceMethod("increment", &ExampleAddon::Increment), // We can also attach plain objects to `exports`, and instance methods as // properties of those sub-objects. InstanceValue("subObject", DefineProperties(Napi::Object::New(env), { InstanceMethod("decrement", &ExampleAddon::Decrement) }), napi_enumerable) }); } private: // This method has access to the data stored in the environment because it is // an instance method of `ExampleAddon` and because it was listed among the // property descriptors passed to `DefineAddon()` in the constructor. Napi::Value Increment(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), ++value); } // This method has access to the data stored in the environment because it is // an instance method of `ExampleAddon` and because it was exposed to // JavaScript by calling `DefineProperties()` with the object onto which it is // attached. Napi::Value Decrement(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), --value); } // Data stored in these variables is unique to each instance of the add-on. uint32_t value = 42; }; // The macro announces that instances of the class `ExampleAddon` will be // created for each instance of the add-on that must be loaded into Node.js. NODE_API_ADDON(ExampleAddon) ``` -------------------------------- ### Get Instance Data from BasicEnv Source: https://github.com/nodejs/node-addon-api/blob/main/doc/basic_env.md Retrieves instance data previously associated with the environment. Returns nullptr if no data was associated. ```cpp template T* GetInstanceData() const; ``` -------------------------------- ### Run Tests Excluding Deprecated Source: https://github.com/nodejs/node-addon-api/blob/main/CONTRIBUTING.md Installs dependencies and runs tests, excluding deprecated API portions. ```bash npm install npm test --disable-deprecated ``` -------------------------------- ### Example of Using HandleScope in a Loop Source: https://github.com/nodejs/node-addon-api/blob/main/doc/handle_scope.md Demonstrates creating a new HandleScope within each iteration of a loop to manage temporary string values. This ensures that 'newValue' is properly handled and can be garbage collected after each iteration. ```cpp for (int i = 0; i < LOOP_MAX; i++) { Napi::HandleScope scope(info.Env()); std::string name = std::string("inner-scope") + std::to_string(i); Napi::Value newValue = Napi::String::New(info.Env(), name.c_str()); // do something with newValue }; ``` -------------------------------- ### JavaScript Usage of Example Addon Source: https://github.com/nodejs/node-addon-api/blob/main/doc/addon.md This JavaScript code demonstrates how to require and use the native 'example_addon'. It shows calling the 'increment' method and accessing a nested 'subObject' to call its 'decrement' method. ```javascript 'use strict' const exampleAddon = require('bindings')('example_addon'); console.log(exampleAddon.increment()); // prints 43 console.log(exampleAddon.increment()); // prints 44 console.log(exampleAddon.subObject.decrement()); // prints 43 ``` -------------------------------- ### JavaScript Usage of Thread-Safe Function Source: https://github.com/nodejs/node-addon-api/blob/main/doc/threadsafe_function.md This JavaScript code shows how to call the native addon's 'start' function. It passes a callback function and the number of times the callback should be invoked. Ensure the addon is correctly required using 'bindings'. ```javascript const { start } = require('bindings')('clock'); start(function () { console.log("JavaScript callback called with arguments", Array.from(arguments)); }, 5); ``` -------------------------------- ### Example: Casting Napi::Date to Double Source: https://github.com/nodejs/node-addon-api/blob/main/doc/date.md Demonstrates casting a Napi::Date object to a double primitive, either by creating a new Date or by accessing an existing one. ```cpp double operatorVal = Napi::Date::New(Env(), 0); // Napi::Date to double // or auto instanceVal = info[0].As().ValueOf(); ``` -------------------------------- ### JavaScript Usage of AsyncProgressWorker Source: https://github.com/nodejs/node-addon-api/blob/main/doc/async_worker_variants.md Example of how to call the native addon that uses Napi::AsyncProgressWorker from JavaScript. ```js const { nativeAddon } = require('binding.node'); const exampleCallback = (errorResponse, okResponse, progressData) => { // Use the data accordingly // ... }; // Call our native addon with the parameters of a string and a function nativeAddon.echo("example", exampleCallback); ``` -------------------------------- ### Creating a Basic Finalizer with Napi::External Source: https://github.com/nodejs/node-addon-api/blob/main/doc/finalization.md Example of creating a Napi::External with a finalizer callback that logs a message and deletes the associated data. This demonstrates a standard finalizer that can access JavaScript. ```cpp Napi::External::New(Env(), new int(1), [](Napi::Env env, int* data) { env.RunScript("console.log('Finalizer called')"); delete data; }); ``` -------------------------------- ### Create and Queue AsyncWorker Instance Source: https://github.com/nodejs/node-addon-api/blob/main/doc/async_worker.md Example of a JavaScript-facing function that creates an instance of a custom AsyncWorker, passing necessary data and a callback, then queues it for execution. ```cpp #include // Include EchoWorker class // .. using namespace Napi; Value Echo(const CallbackInfo& info) { // You need to validate the arguments here. Function cb = info[1].As(); std::string in = info[0].As(); EchoWorker* wk = new EchoWorker(cb, in); wk->Queue(); return info.Env().Undefined(); } ``` -------------------------------- ### Get the Environment of a Napi::Reference Source: https://github.com/nodejs/node-addon-api/blob/main/doc/reference.md The `Env` method returns the `Napi::Env` associated with the `Napi::Reference` instance. ```cpp Napi::Env Napi::Reference::Env() const; ``` -------------------------------- ### Get Byte Offset of DataView Source: https://github.com/nodejs/node-addon-api/blob/main/doc/dataview.md Returns the offset into the underlying buffer where the DataView starts, measured in bytes. ```cpp size_t Napi::DataView::ByteOffset() const; ``` -------------------------------- ### Get Byte Offset Source: https://github.com/nodejs/node-addon-api/blob/main/doc/typed_array.md Returns the offset, in bytes, from the beginning of the backing ArrayBuffer to the start of the TypedArray data. This is important for views into larger buffers. ```cpp size_t Napi::TypedArray::ByteOffset() const; ``` -------------------------------- ### Build and Run Release Tests with Ninja Source: https://github.com/nodejs/node-addon-api/blob/main/doc/contributing/build_with_ninja.md Build the tests using Ninja for the Release configuration and then run them. Ensure you have configured with Ninja first. ```sh /node-addon-api $ ninja -C test/build/Release # Run tests /node-addon-api $ node ./test/index.js ``` -------------------------------- ### Get Data Pointer Source: https://github.com/nodejs/node-addon-api/blob/main/doc/typed_array_of.md Returns a raw pointer to the underlying ArrayBuffer's data, offset to the start of the typed array. Use with caution as it bypasses N-API type checking. ```cpp T* Napi::TypedArrayOf::Data() const; ``` -------------------------------- ### Get Node.js Version Information Source: https://github.com/nodejs/node-addon-api/blob/main/doc/version_management.md Retrieves a pointer to the napi_node_version structure containing Node.js version details. The environment must be provided. ```cpp static const napi_node_version* Napi::VersionManagement::GetNodeVersion(Napi::BasicEnv env); ``` -------------------------------- ### MakeCallback with AsyncContext Example Source: https://github.com/nodejs/node-addon-api/blob/main/doc/async_context.md Demonstrates how to create and use Napi::AsyncContext with Napi::Function::MakeCallback to invoke a callback with the correct async execution context. The context is automatically destroyed when it goes out of scope. ```cpp #include "napi.h" void MakeCallbackWithAsyncContext(const Napi::CallbackInfo& info) { Napi::Function callback = info[0].As(); Napi::Object resource = info[1].As(); // Create a new async context instance. Napi::AsyncContext context(info.Env(), "async_context_test", resource); // Invoke the callback with the async context instance. callback.MakeCallback(Napi::Object::New(info.Env()), std::initializer_list{}, context); // The async context instance is automatically destroyed here because it's // block-scope like `Napi::HandleScope`. } ``` -------------------------------- ### C++ Entry Point for Node.js Addon using napi.h Source: https://github.com/nodejs/node-addon-api/blob/main/doc/node-gyp.md Initializes the Node.js addon by defining the entry point and exporting functions. The NODE_API_MODULE macro links the C++ entry point to the addon's target name. ```cpp #include // ... /** * This code is our entry point. We receive two arguments here: the first is the * environment that represent an independent instance of the JavaScript runtime; * the second is exports, the same as module.exports in a .js file. * You can either add properties to the exports object passed in or create your * own exports object. In either case you must return the object to be used as * the exports for the module when you return from the Init function. */ Napi::Object Init(Napi::Env env, Napi::Object exports) { // ... return exports; } /** * This code defines the entry point for the Node addon. It tells Node where to go * once the library has been loaded into active memory. The first argument must * match the "target" in our *binding.gyp*. Using NODE_GYP_MODULE_NAME ensures * that the argument will be correct, as long as the module is built with * node-gyp (which is the usual way of building modules). The second argument * points to the function to invoke. The function must not be namespaced. */ NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) ``` -------------------------------- ### Create Instance Method Descriptor (void return) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/instance_wrap.md Use this to create a property descriptor for an instance method that does not return a value. The native method signature must be `void MethodName(const Napi::CallbackInfo& info);`. ```cpp template template ::InstanceVoidMethodCallback method> static Napi::ClassPropertyDescriptor Napi::InstanceWrap::InstanceMethod(const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); ``` -------------------------------- ### JavaScript Usage of External with Finalizers Source: https://github.com/nodejs/node-addon-api/blob/main/doc/finalization.md Example JavaScript code demonstrating how to use the native addon's `createExternal` function and the expected output when finalizers are executed. ```js // JavaScript const { createExternal } = require('./addon.node'); for (let i = 0; i < 5; i++) { const ext = createExternal(); // ... do something with `ext` .. } console.log('Loop complete'); await new Promise(resolve => setImmediate(resolve)); console.log('Next event loop cycle'); ``` -------------------------------- ### Napi::CallbackInfo Constructor Source: https://github.com/nodejs/node-addon-api/blob/main/doc/callbackinfo.md Constructs a Napi::CallbackInfo object from the provided environment and callback info. ```APIDOC ## Napi::CallbackInfo Constructor ### Description Constructs a Napi::CallbackInfo object from the provided environment and callback info. ### Parameters #### Path Parameters - **env** (napi_env) - Required - The napi_env environment in which to construct the Napi::CallbackInfo object. - **info** (napi_callback_info) - Required - The napi_callback_info data structure from which to construct the Napi::CallbackInfo object. ``` -------------------------------- ### Create and Use ObjectReference Source: https://github.com/nodejs/node-addon-api/blob/main/doc/object_reference.md Creates an ObjectReference with an initial reference count, sets properties, and retrieves them. Ensure Napi::Object is available. ```cpp #include using namespace Napi; void Init(Env env) { // Create an empty ObjectReference that has an initial reference count of 2. ObjectReference obj_ref = Reference::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); } ``` -------------------------------- ### Get Module File Name Source: https://github.com/nodejs/node-addon-api/blob/main/doc/basic_env.md Retrieves the absolute path of the add-on's loaded location as a null-terminated string. The string is valid only while the add-on is loaded. ```cpp const char* Napi::Env::GetModuleFileName() const; ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/nodejs/node-addon-api/blob/main/benchmark/README.md Execute all benchmarks from the parent directory using the npm script. Supports filtering benchmarks by name. ```bash npm run-script benchmark ``` -------------------------------- ### Napi::AsyncWorker::Cancel Source: https://github.com/nodejs/node-addon-api/blob/main/doc/async_worker.md 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. ```APIDOC ## Napi::AsyncWorker::Cancel ### Description 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. ### Method ### Signature ```cpp void Napi::AsyncWorker::Cancel(); ``` ``` -------------------------------- ### Creating a Basic Finalizer with Napi::ArrayBuffer Source: https://github.com/nodejs/node-addon-api/blob/main/doc/finalization.md Example of creating a Napi::ArrayBuffer with a basic finalizer. Basic finalizers are intended for scenarios where JavaScript access is not needed, potentially allowing for engine optimizations. ```cpp Napi::ArrayBuffer::New( Env(), data, length, [](Napi::BasicEnv /*env*/, void* finalizeData) { delete[] static_cast(finalizeData); }); ``` -------------------------------- ### Get Object Prototype Source: https://github.com/nodejs/node-addon-api/blob/main/doc/object.md Retrieves the prototype of a JavaScript object. ```cpp Napi::Object Napi::Object::GetPrototype() const; ``` -------------------------------- ### Get Null Value Source: https://github.com/nodejs/node-addon-api/blob/main/doc/env.md Retrieves the JavaScript Null Object from the environment. ```cpp Napi::Value Napi::Env::Null() const; ``` -------------------------------- ### Empty String Constructor Source: https://github.com/nodejs/node-addon-api/blob/main/doc/string.md Creates a new, empty Napi::String instance. Throws Napi::Error on failure. ```cpp Napi::String::String(); ``` -------------------------------- ### Get Undefined Value Source: https://github.com/nodejs/node-addon-api/blob/main/doc/env.md Retrieves the JavaScript Undefined Object from the environment. ```cpp Napi::Value Napi::Env::Undefined() const; ``` -------------------------------- ### Napi::CallbackInfo::Length Source: https://github.com/nodejs/node-addon-api/blob/main/doc/callbackinfo.md Gets the number of arguments passed to the callback. ```APIDOC ## Napi::CallbackInfo::Length ### Description Returns the number of arguments passed in the Napi::CallbackInfo object. ### Method GET ### Endpoint Napi::CallbackInfo::Length() ### Response #### Success Response (200) - **size_t** - The number of arguments. ``` -------------------------------- ### Create Instance Method Descriptor (Napi::Value return) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/instance_wrap.md Use this to create a property descriptor for an instance method that returns a `Napi::Value`. The native method signature must be `Napi::Value MethodName(const Napi::CallbackInfo& info);`. ```cpp template template ::InstanceMethodCallback method> static Napi::ClassPropertyDescriptor Napi::InstanceWrap::InstanceMethod(const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); ``` -------------------------------- ### Get Callback Data Source: https://github.com/nodejs/node-addon-api/blob/main/doc/callbackinfo.md Retrieves the data pointer associated with the callback. ```cpp void* Napi::CallbackInfo::Data() const; ``` -------------------------------- ### Napi::Addon Constructor Source: https://github.com/nodejs/node-addon-api/blob/main/doc/addon.md Creates a new instance of the add-on. It requires the environment and the exports object from JavaScript. ```cpp Napi::Addon(Napi::Env env, Napi::Object exports); ``` -------------------------------- ### JavaScript Usage of TypedThreadSafeFunction Addon Source: https://github.com/nodejs/node-addon-api/blob/main/doc/typed_threadsafe_function.md This JavaScript code demonstrates how to require and use the native addon that utilizes TypedThreadSafeFunction. It shows how to call the native 'start' function and provide a callback for receiving data. ```js const { start } = require('bindings')('clock'); start.call(new Date(), function (clock) { const context = this; console.log(context, clock); }, 5); ``` -------------------------------- ### Napi::TypedArray::ByteOffset() Source: https://github.com/nodejs/node-addon-api/blob/main/doc/typed_array.md Returns the byte offset into the ArrayBuffer where the TypedArray starts. ```APIDOC ## Napi::TypedArray::ByteOffset() ### Description Returns the offset into the `Napi::ArrayBuffer` where the array starts, in bytes. ### Method `ByteOffset` ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response - **return value** (size_t) - The offset into the `Napi::ArrayBuffer` in bytes. ``` -------------------------------- ### Configure Build with Ninja Source: https://github.com/nodejs/node-addon-api/blob/main/doc/contributing/build_with_ninja.md Configure the project to use Ninja as the build system for tests. This command should be run from the project root. ```sh /node-addon-api $ node-gyp configure -C test -- -f ninja ``` -------------------------------- ### Napi::DataView::ByteOffset() Source: https://github.com/nodejs/node-addon-api/blob/main/doc/dataview.md Returns the offset into the DataView where the array starts, in bytes. ```APIDOC ## Napi::DataView::ByteOffset() ### Description Returns the offset into the `Napi::DataView` where the array starts, in bytes. ### Method size_t ### Returns The byte offset. ``` -------------------------------- ### Navigate to Module Directory Source: https://github.com/nodejs/node-addon-api/blob/main/doc/conversion-tool.md Change to your module's directory before running the conversion script. ```bash cd [module_path] ``` -------------------------------- ### Get Napi::Value Type Source: https://github.com/nodejs/node-addon-api/blob/main/doc/value.md Returns the napi_valuetype type of the Napi::Value. ```cpp napi_valuetype Napi::Value::Type() const; ``` -------------------------------- ### Create and Manipulate JavaScript Object Properties Source: https://github.com/nodejs/node-addon-api/blob/main/doc/object.md Demonstrates creating a new JavaScript object, setting properties with string and uint32 keys, retrieving property values, and checking for property existence. ```cpp #include 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(uint32_t(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(uint32_t(42)); Value val3 = obj.Get("Douglas Adams"); // Test if objects have properties. bool obj1 = obj.Has("hello"); // true bool obj2 = obj.Has("world"); // false } ``` -------------------------------- ### Get Byte Length of DataView Source: https://github.com/nodejs/node-addon-api/blob/main/doc/dataview.md Returns the total length of the DataView in bytes. ```cpp size_t Napi::DataView::ByteLength() const; ``` -------------------------------- ### Get Global Object Source: https://github.com/nodejs/node-addon-api/blob/main/doc/env.md Retrieves the JavaScript Global Object associated with the environment. ```cpp Napi::Object Napi::Env::Global() const; ``` -------------------------------- ### Create Instance Method Descriptor using Symbol (void return) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/instance_wrap.md Use this overload to create a property descriptor for an instance method using a `Napi::Symbol` for its name. The native method signature must be `void MethodName(const Napi::CallbackInfo& info);`. ```cpp template template ::InstanceVoidMethodCallback method> static Napi::ClassPropertyDescriptor Napi::InstanceWrap::InstanceMethod(Napi::Symbol name, napi_property_attributes attributes = napi_default, void* data = nullptr); ``` -------------------------------- ### Set Instance Data with Hint and Default Finalizer Source: https://github.com/nodejs/node-addon-api/blob/main/doc/basic_env.md Associates data and a hint with the add-on instance. The default finalizer is used when the add-on unloads. ```cpp template using FinalizerWithHint = void (*)(Env, DataType*, HintType*); template fini = Env::DefaultFiniWithHint> void SetInstanceData(DataType* data, HintType* hint) const; ``` -------------------------------- ### Napi::BigInt::WordCount Source: https://github.com/nodejs/node-addon-api/blob/main/doc/bigint.md Gets the number of words required to store the BigInt value. ```APIDOC ## Napi::BigInt::WordCount ### Description Returns the number of words needed to store this `BigInt` value. ### Method `size_t Napi::BigInt::WordCount() const` ### Response Returns the number of words needed to store this `BigInt` value. ``` -------------------------------- ### Get 'this' Value Source: https://github.com/nodejs/node-addon-api/blob/main/doc/callbackinfo.md Retrieves the JavaScript 'this' value for the current function invocation. ```cpp Napi::Value Napi::CallbackInfo::This() const; ``` -------------------------------- ### Napi::BasicEnv Constructor Source: https://github.com/nodejs/node-addon-api/blob/main/doc/basic_env.md Constructs a Napi::BasicEnv object from a node_api_nogc_env environment. ```APIDOC ## Constructor Napi::BasicEnv::BasicEnv ### Description Constructs a `Napi::BasicEnv` object from a `node_api_nogc_env` environment. ### Parameters #### Path Parameters - **env** (node_api_nogc_env) - in - The `node_api_nogc_env` environment from which to construct the `Napi::BasicEnv` object. ``` -------------------------------- ### Get Argument Count Source: https://github.com/nodejs/node-addon-api/blob/main/doc/callbackinfo.md Returns the total number of arguments passed to the JavaScript function. ```cpp size_t Napi::CallbackInfo::Length() const; ``` -------------------------------- ### Configure binding.gyp for Node-API (All C++ Exceptions) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/setup.md Include the node_addon_api_except_all target in your binding.gyp file to catch all native C++ exceptions. ```gyp 'dependencies': [ " #include #include "napi.h" using namespace Napi; // A structure representing some data that uses a "large" amount of memory. class LargeData { public: LargeData() : id(instances++) {} size_t id; static size_t instances; }; size_t LargeData::instances = 0; // Basic finalizer to free `LargeData`. Takes ownership of the pointer and // frees its memory after use. void MyBasicFinalizer(Napi::BasicEnv env, LargeData* data) { std::unique_ptr instance(data); std::cout << "Basic finalizer for instance " << instance->id << " called\n"; // Register a finalizer. Since the instance will be deleted by // the time this callback executes, pass the instance's `id` via lambda copy // capture and _not_ a reference capture that accesses `this`. env.PostFinalizer([instanceId = instance->id](Napi::Env env) { env.RunScript("console.log('Finalizer for instance " + std::to_string(instanceId) + " called');"); }); // Free the `LargeData` held in `data` once `instance` goes out of scope. } Value CreateExternal(const CallbackInfo& info) { // Create a new instance of LargeData. auto instance = std::make_unique(); // Wrap the instance in an External object, registering a basic // finalizer that will delete the instance to free the "large" amount of // memory. return External::New(info.Env(), instance.release(), MyBasicFinalizer); } Object Init(Napi::Env env, Object exports) { exports["createExternal"] = Function::New(env, CreateExternal); return exports; } NODE_API_MODULE(addon, Init) ``` -------------------------------- ### Get node_api_nogc_env from BasicEnv Source: https://github.com/nodejs/node-addon-api/blob/main/doc/basic_env.md Returns the underlying node_api_nogc_env opaque data structure representing the environment. ```cpp operator node_api_nogc_env() const; ``` -------------------------------- ### Retrieve Addon Instance from Environment Source: https://github.com/nodejs/node-addon-api/blob/main/doc/addon.md This C++ snippet shows how to retrieve the instance of the Napi::Addon class from the Napi::Env object using GetInstanceData. This is useful when implementing functions that need access to the add-on's instance data. ```cpp void ExampleBinding(const Napi::CallbackInfo& info) { ExampleAddon* addon = info.Env().GetInstanceData(); } ``` -------------------------------- ### Get Mutable Iterator to End Source: https://github.com/nodejs/node-addon-api/blob/main/doc/object.md Returns a non-constant iterator pointing to the end of the object's properties. ```cpp Napi::Object::iterator Napi::Object::end(); ``` -------------------------------- ### Configure binding.gyp for Node-API (No Exceptions) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/setup.md Include the base node_addon_api target in your binding.gyp file when not using C++ exceptions. ```gyp 'dependencies': [ "(info){ ... } ``` -------------------------------- ### Get and Clear Pending Exception Source: https://github.com/nodejs/node-addon-api/blob/main/doc/env.md Retrieves and clears any pending exception from the environment, returning it as an Napi::Error object. ```cpp Napi::Error Napi::Env::GetAndClearPendingException() const; ``` -------------------------------- ### Create Instance Method Descriptor using Symbol (Napi::Value return) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/instance_wrap.md Use this overload to create a property descriptor for an instance method using a `Napi::Symbol` for its name, where the method returns a `Napi::Value`. The native method signature must be `Napi::Value MethodName(const Napi::CallbackInfo& info);`. ```cpp template template ::InstanceMethodCallback method> static Napi::ClassPropertyDescriptor Napi::InstanceWrap::InstanceMethod(Napi::Symbol name, napi_property_attributes attributes = napi_default, void* data = nullptr); ``` -------------------------------- ### Constructor for Napi::ClassPropertyDescriptor Source: https://github.com/nodejs/node-addon-api/blob/main/doc/class_property_descriptor.md This C++ code shows the constructor for Napi::ClassPropertyDescriptor. It takes a napi_property_descriptor as input and initializes the internal descriptor. ```cpp Napi::ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} ``` -------------------------------- ### Get New Target Source: https://github.com/nodejs/node-addon-api/blob/main/doc/callbackinfo.md Retrieves the 'new.target' value for constructor calls. Returns an empty Value if the invocation was not a constructor. ```cpp Napi::Value Napi::CallbackInfo::NewTarget() const; ``` -------------------------------- ### Constructor (callback, resource_name) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/async_worker.md Creates a new Napi::AsyncWorker with a callback function and a resource name. ```APIDOC ## Constructor ### Description Creates a new `Napi::AsyncWorker`. ### Signature ```cpp explicit Napi::AsyncWorker(const Napi::Function& callback, const char* resource_name); ``` ### Parameters * `[in] callback` (Napi::Function) - 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` (const char*) - Null-terminated string that represents the identifier for the kind of resource that is being provided for diagnostic information exposed by the async_hooks API. ### Returns A `Napi::AsyncWorker` instance which can later be queued for execution by calling `Napi::AsyncWork::Queue`. ``` -------------------------------- ### Creating a Uint8ClampedArray Source: https://github.com/nodejs/node-addon-api/blob/main/doc/typed_array_of.md Special handling is required for Uint8ClampedArray due to its clamping behavior. This example shows the explicit initialization needed. ```cpp Uint8Array::New(env, length, napi_uint8_clamped_array) ``` -------------------------------- ### Napi::TypedThreadSafeFunction::Acquire Source: https://github.com/nodejs/node-addon-api/blob/main/doc/typed_threadsafe_function.md Acquires the thread-safe function for use by a new thread, indicating that the thread will start making use of it. ```APIDOC ## Napi::TypedThreadSafeFunction::Acquire ### Description Adds a thread to this thread-safe function object, indicating that a new thread will start making use of the thread-safe function. ### Method Instance Method ### Parameters None ### Response Returns one of: - `napi_ok`: The thread has successfully acquired the thread-safe function for its use. - `napi_closing`: The thread-safe function has been marked as closing via a previous call to `Abort()`. ### Request Example ```cpp napi_status Napi::TypedThreadSafeFunction::Acquire(); ``` ``` -------------------------------- ### DefineAddon Method Source: https://github.com/nodejs/node-addon-api/blob/main/doc/addon.md Defines an add-on instance with properties. Use this to attach methods, accessors, and values to the exports object. ```cpp template void Napi::Addon::DefineAddon(Napi::Object exports, const std::initializer_list& properties); ``` -------------------------------- ### Napi::ThreadSafeFunction::Acquire Source: https://github.com/nodejs/node-addon-api/blob/main/doc/threadsafe_function.md Adds a thread to this thread-safe function object, indicating that a new thread will start making use of it. ```APIDOC ## Acquire Add a thread to this thread-safe function object, indicating that a new thread will start making use of the thread-safe function. ```cpp napi_status Napi::ThreadSafeFunction::Acquire() const ``` Returns one of: - `napi_ok`: The thread has successfully acquired the thread-safe function for its use. - `napi_closing`: The thread-safe function has been marked as closing via a previous call to `Abort()`. ``` -------------------------------- ### Construct Napi::BasicEnv Source: https://github.com/nodejs/node-addon-api/blob/main/doc/basic_env.md Constructs a Napi::BasicEnv object from a node_api_nogc_env environment. ```cpp Napi::BasicEnv::BasicEnv(node_api_nogc_env env); ``` -------------------------------- ### Get Mutable Iterator to Beginning Source: https://github.com/nodejs/node-addon-api/blob/main/doc/object.md Returns a non-constant iterator pointing to the beginning of the object's properties, allowing modification. ```cpp Napi::Object::iterator Napi::Object::begin(); ``` -------------------------------- ### Napi::AsyncWorker Constructor (env) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/async_worker.md Creates a new Napi::AsyncWorker instance using the provided environment. This instance can then be queued for execution. ```APIDOC ### Constructor Creates a new `Napi::AsyncWorker`. ```cpp explicit Napi::AsyncWorker(Napi::Env env); ``` ### Parameters * `[in] env` (Napi::Env) - The environment in which to create the `Napi::AsyncWorker`. Returns an `Napi::AsyncWorker` instance which can later be queued for execution by calling `Napi::AsyncWorker::Queue`. ``` -------------------------------- ### Configure binding.gyp for Node-API (Napi::Error Exceptions) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/setup.md Include the node_addon_api_except target in your binding.gyp file to catch Napi::Error exceptions. ```gyp 'dependencies': [ "("Func1"), InstanceMethod<&[ClassName]::Func2>("Func2"), InstanceAccessor<&[ClassName]::ValueGetter>("Value"), StaticMethod<&[ClassName]::StaticMethod>("MethodName"), InstanceValue("Value", Napi::[Type]::New(env, value)), }); constructor = Napi::Persistent(ctor); constructor .SuppressDestruct(); exports.Set("[ClassName]", ctor); } ``` -------------------------------- ### Get Element Size Source: https://github.com/nodejs/node-addon-api/blob/main/doc/typed_array.md Returns the size, in bytes, of a single element within the TypedArray. This is determined by the specific TypedArray type. ```cpp uint8_t Napi::TypedArray::ElementSize() const; ``` -------------------------------- ### AsyncContext Constructor with Resource Name Source: https://github.com/nodejs/node-addon-api/blob/main/doc/async_context.md Creates a new Napi::AsyncContext instance. Requires the environment and a resource name for diagnostic information. ```cpp explicit Napi::AsyncContext::AsyncContext(napi_env env, const char* resource_name); ``` -------------------------------- ### Get Backing ArrayBuffer Source: https://github.com/nodejs/node-addon-api/blob/main/doc/typed_array.md Returns the underlying ArrayBuffer that holds the data for the TypedArray. Use this when you need to access the raw buffer. ```cpp Napi::ArrayBuffer Napi::TypedArray::ArrayBuffer() const; ``` -------------------------------- ### Initialize Empty DataView Source: https://github.com/nodejs/node-addon-api/blob/main/doc/dataview.md Initializes an empty instance of the Napi::DataView class. This creates a DataView that does not reference any underlying buffer. ```cpp Napi::DataView(); ``` -------------------------------- ### Get Node-API Version Source: https://github.com/nodejs/node-addon-api/blob/main/doc/version_management.md Retrieves the highest Node-API version supported by the Node.js runtime. Pass the environment to this static method. ```cpp static uint32_t Napi::VersionManagement::GetNapiVersion(Napi::BasicEnv env); ``` -------------------------------- ### Get Buffer Length Source: https://github.com/nodejs/node-addon-api/blob/main/doc/buffer.md Retrieve the number of elements in the external data buffer. This is useful for understanding the size of the data being managed. ```cpp size_t Napi::Buffer::Length() const; ``` -------------------------------- ### InstanceMethod (non-void return, string name) Source: https://github.com/nodejs/node-addon-api/blob/main/doc/instance_wrap.md Creates a property descriptor for a native C++ method that returns a `Napi::Value` and is identified by a UTF-8 string name. This method is invoked on JavaScript instances of a class wrapped by `InstanceWrap`. ```APIDOC ## InstanceMethod (non-void return, string name) ### Description Creates a property descriptor that represents a method returning a `Napi::Value` exposed on JavaScript instances of a class. ### Method Signature ```cpp template template ::InstanceMethodCallback method> static Napi::ClassPropertyDescriptor Napi::InstanceWrap::InstanceMethod(const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); ``` ### Parameters * `method` (InstanceWrap::InstanceMethodCallback) - Required - The native function that represents the method. * `utf8name` (const char*) - Required - The null-terminated string name of the method. * `attributes` (napi_property_attributes) - Optional - Attributes for the property (e.g., `napi_default`). * `data` (void*) - Optional - User-provided data passed to the method. ### Returns A `Napi::ClassPropertyDescriptor` object representing the instance method. ``` -------------------------------- ### Get Error Message Source: https://github.com/nodejs/node-addon-api/blob/main/doc/error.md Retrieves a reference to the string representing the error message. This method is useful for inspecting the details of an error. ```cpp std::string& Napi::Error::Message() const NAPI_NOEXCEPT; ``` -------------------------------- ### Constructor for Napi::Env Source: https://github.com/nodejs/node-addon-api/blob/main/doc/env.md Constructs a Napi::Env object from a napi_env environment. ```cpp Napi::Env::Env(napi_env env); ```