### Run NAN Tests Source: https://github.com/nodejs/nan/blob/main/README.md Instructions for installing dependencies and running the NAN test suite. ```sh npm install npm run-script rebuild-tests npm test ``` ```sh npm install make test ``` -------------------------------- ### Basic Example Source: https://github.com/nodejs/nan/blob/main/doc/object_wrappers.md Demonstrates how to create a custom JavaScript class `MyObject` using `Nan::ObjectWrap` in a Node.js add-on. ```APIDOC ## Basic Example This example shows how to define a C++ class `MyObject` that inherits from `Nan::ObjectWrap` and expose it to JavaScript. ### C++ Code ```c++ #include class MyObject : public Nan::ObjectWrap { public: static NAN_MODULE_INIT(Init) { v8::Local tpl = Nan::New(New); tpl->SetClassName(Nan::New("MyObject").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "getHandle", GetHandle); Nan::SetPrototypeMethod(tpl, "getValue", GetValue); constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); Nan::Set(target, Nan::New("MyObject").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } private: explicit MyObject(double value = 0) : value_(value) {} ~MyObject() {} static NAN_METHOD(New) { if (info.IsConstructCall()) { double value = info[0]->IsUndefined() ? 0 : Nan::To(info[0]).FromJust(); MyObject *obj = new MyObject(value); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { const int argc = 1; v8::Local argv[argc] = {info[0]}; v8::Local cons = Nan::New(constructor()); info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); } } static NAN_METHOD(GetHandle) { MyObject* obj = Nan::ObjectWrap::Unwrap(info.Holder()); info.GetReturnValue().Set(obj->handle()); } static NAN_METHOD(GetValue) { MyObject* obj = Nan::ObjectWrap::Unwrap(info.Holder()); info.GetReturnValue().Set(obj->value_); } static inline Nan::Persistent & constructor() { static Nan::Persistent my_constructor; return my_constructor; } double value_; }; NODE_MODULE(objectwrapper, MyObject::Init) ``` ### JavaScript Usage ```javascript var objectwrapper = require('bindings')('objectwrapper'); var obj = new objectwrapper.MyObject(5); console.log('Should be 5: ' + obj.getValue()); ``` ``` -------------------------------- ### Basic Nan::ObjectWrap Example Source: https://github.com/nodejs/nan/blob/main/doc/object_wrappers.md Demonstrates how to create a custom C++ class `MyObject` that inherits from Nan::ObjectWrap. This example shows initialization, wrapping, and unwrapping for JavaScript interaction. ```c++ class MyObject : public Nan::ObjectWrap { public: static NAN_MODULE_INIT(Init) { v8::Local tpl = Nan::New(New); tpl->SetClassName(Nan::New("MyObject").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "getHandle", GetHandle); Nan::SetPrototypeMethod(tpl, "getValue", GetValue); constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); Nan::Set(target, Nan::New("MyObject").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } private: explicit MyObject(double value = 0) : value_(value) {} ~MyObject() {} static NAN_METHOD(New) { if (info.IsConstructCall()) { double value = info[0]->IsUndefined() ? 0 : Nan::To(info[0]).FromJust(); MyObject *obj = new MyObject(value); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { const int argc = 1; v8::Local argv[argc] = {info[0]}; v8::Local cons = Nan::New(constructor()); info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); } } static NAN_METHOD(GetHandle) { MyObject* obj = Nan::ObjectWrap::Unwrap(info.Holder()); info.GetReturnValue().Set(obj->handle()); } static NAN_METHOD(GetValue) { MyObject* obj = Nan::ObjectWrap::Unwrap(info.Holder()); info.GetReturnValue().Set(obj->value_); } static inline Nan::Persistent & constructor() { static Nan::Persistent my_constructor; return my_constructor; } double value_; }; NODE_MODULE(objectwrapper, MyObject::Init) ``` ```javascript var objectwrapper = require('bindings')('objectwrapper'); var obj = new objectwrapper.MyObject(5); console.log('Should be 5: ' + obj.getValue()); ``` -------------------------------- ### Getter Declaration Example Source: https://github.com/nodejs/nan/blob/main/doc/methods.md Provides an example of declaring a getter function with the correct signature for use with Node-API. ```c++ void GetterName(v8::Local property, const Nan::PropertyCallbackInfo& info) { ... } ``` -------------------------------- ### Install NAN Package Source: https://github.com/nodejs/nan/blob/main/README.md Add NAN as a dependency using a package manager like npm, yarn, or bun. ```bash $ npm install nan ``` -------------------------------- ### Method Declaration Example Source: https://github.com/nodejs/nan/blob/main/doc/methods.md Illustrates how to declare static methods within a class inheriting from Nan::ObjectWrap, intended for JavaScript exposure. ```c++ // .h: class Foo : public Nan::ObjectWrap { ... static void Bar(const Nan::FunctionCallbackInfo& info); static void Baz(const Nan::FunctionCallbackInfo& info); } // .cc: void Foo::Bar(const Nan::FunctionCallbackInfo& info) { ... } void Foo::Baz(const Nan::FunctionCallbackInfo& info) { ... } ``` -------------------------------- ### Nan::ReturnValue Example Usage Source: https://github.com/nodejs/nan/blob/main/doc/methods.md Demonstrates setting a return value using Nan::ReturnValue in a function callback. Ensure a HandleScope is active when calling this. ```c++ void EmptyArray(const Nan::FunctionCallbackInfo& info) { info.GetReturnValue().Set(Nan::New()); } ``` -------------------------------- ### Weak Callback Implementation Source: https://github.com/nodejs/nan/blob/main/doc/persistent.md Example of implementing a weak callback function to free associated memory. ```c++ void weakCallback(const WeakCallbackInfo &data) { int *parameter = data.GetParameter(); delete parameter; } ``` -------------------------------- ### Get Start Column of V8 Message Source: https://github.com/nodejs/nan/blob/main/doc/maybe_types.md Use Nan::GetStartColumn to safely retrieve the starting column of a V8 message. This helper ensures compatibility with various V8 versions. ```c++ Nan::Maybe Nan::GetStartColumn(v8::Local msg); ``` -------------------------------- ### Nan::Get Source: https://github.com/nodejs/nan/blob/main/doc/maybe_types.md A helper method for calling v8::Object#Get() in a way compatible across supported versions of V8. ```APIDOC ## Nan::Get() ### Description A helper method for calling [`v8::Object#Get()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a2565f03e736694f6b1e1cf22a0b4eac2) in a way compatible across supported versions of V8. ### Signature ```cpp Nan::MaybeLocal Nan::Get(v8::Local obj, v8::Local key); Nan::MaybeLocal Nan::Get(v8::Local obj, uint32_t index); ``` ``` -------------------------------- ### Node.js 0.12 OSX Compilation Error Example Source: https://github.com/nodejs/nan/blob/main/README.md This C++ compilation error occurs when building Node.js addons against Node.js 0.12 on OSX with newer compilers. It indicates an issue with v8 headers and the 'CreateHandle' member of 'v8::HandleScope'. A workaround involves patching v8.h. ```cpp ❯ CXX(target) Release/obj.target/accessors/cpp/accessors.o In file included from ../cpp/accessors.cpp:9: In file included from ../../nan.h:51: In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61: /Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope' return Handle(reinterpret_cast(HandleScope::CreateHandle( ~~~~~~~~~~~~~^~~~~~~~~~~~ ``` -------------------------------- ### Basic Nan::Callback Usage Source: https://github.com/nodejs/nan/blob/main/doc/callback.md Demonstrates the basic instantiation and invocation of a Nan::Callback. Ensure the v8::Local is valid before creating the callback. ```c++ v8::Local function; Nan::Callback callback(function); callback.Call(0, 0); ``` -------------------------------- ### Setting a Weak Persistent Reference Source: https://github.com/nodejs/nan/blob/main/doc/persistent.md Demonstrates how to set a weak persistent reference with a parameter for the callback. ```c++ Persistent obj; int *data = new int(0); obj.SetWeak(data, callback, WeakCallbackType::kParameter); ``` -------------------------------- ### Nan::GetIsolateData() Source: https://github.com/nodejs/nan/blob/main/doc/v8_misc.md Retrieves data associated with a V8 isolate. This function offers a consistent way to get isolate-specific data. ```APIDOC ## Nan::GetIsolateData() ### Description A helper to provide a consistent API to `v8::Isolate#GetData()`. ### Signature ```c++ T *Nan::GetIsolateData(v8::Isolate *isolate) ``` ``` -------------------------------- ### Nan::NewInstance() Source: https://github.com/nodejs/nan/blob/main/doc/maybe_types.md A helper method for calling `v8::Function#NewInstance()` and `v8::ObjectTemplate#NewInstance()` in a way compatible across supported versions of V8. ```APIDOC ## Nan::NewInstance() ### Description A helper method for calling [`v8::Function#NewInstance()`](https://v8docs.nodesource.com/node-8.16/d5/d54/classv8_1_1_function.html#ae477558b10c14b76ed00e8dbab44ce5b) and [`v8::ObjectTemplate#NewInstance()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#ad605a7543cfbc5dab54cdb0883d14ae4) in a way compatible across supported versions of V8. ### Signatures ```c++ Nan::MaybeLocal Nan::NewInstance(v8::Local h); Nan::MaybeLocal Nan::NewInstance(v8::Local h, int argc, v8::Local argv[]); Nan::MaybeLocal Nan::NewInstance(v8::Local h); ``` ``` -------------------------------- ### Javascript Usage of Factory Object Source: https://github.com/nodejs/nan/blob/main/doc/object_wrappers.md Demonstrates how to require and instantiate the C++ factory object from Javascript, and call its methods. ```javascript var wrappedobjectfactory = require('bindings')('wrappedobjectfactory'); var obj = wrappedobjectfactory.newFactoryObjectInstance(10); console.log('Should be 10: ' + obj.getValue()); ``` -------------------------------- ### NAN_MODULE_INIT Source: https://github.com/nodejs/nan/blob/main/doc/node_misc.md Defines the entry point function for a Node.js add-on. It creates a function named `name` that accepts a `target` object, which is equivalent to the JavaScript `exports` object. ```APIDOC ## NAN_MODULE_INIT() ### Description Used to define the entry point function to a Node add-on. Creates a function with a given `name` that receives a `target` object representing the equivalent of the JavaScript `exports` object. ### Example ```c++ NAN_MODULE_INIT(Init) { NAN_EXPORT(target, Foo); } ``` ``` -------------------------------- ### Get External Value Source: https://github.com/nodejs/nan/blob/main/doc/v8_internals.md Reads the pointer stored within a v8::External object. It applies a default tag for compatibility with different V8 versions. ```c++ void* Nan::GetExternalValue(v8::Local ext) ``` -------------------------------- ### Javascript Usage for Summing Wrapped Objects Source: https://github.com/nodejs/nan/blob/main/doc/object_wrappers.md Shows how to use the `sum` function exported from the C++ addon, passing it instances of the wrapped objects created previously. ```javascript var myaddon = require('bindings')('myaddon'); var obj1 = myaddon.newFactoryObjectInstance(5); var obj2 = myaddon.newFactoryObjectInstance(10); console.log('sum of object values: ' + myaddon.sum(obj1, obj2)); ``` -------------------------------- ### Get Internal Field Pointer Source: https://github.com/nodejs/nan/blob/main/doc/v8_internals.md Retrieves a pointer to an internal field of a V8 object. The specific V8 API used depends on the V8 version. ```c++ void* Nan::GetInternalFieldPointer(v8::Local object, int index) ``` -------------------------------- ### Get Heap Statistics Source: https://github.com/nodejs/nan/blob/main/doc/v8_internals.md Retrieve V8's heap statistics into a provided v8::HeapStatistics object. This function wraps V8's GetHeapStatistics. ```c++ void Nan::GetHeapStatistics(v8::HeapStatistics *heap_statistics) ``` -------------------------------- ### Factory of wrapped objects Source: https://github.com/nodejs/nan/blob/main/doc/object_wrappers.md This section demonstrates how to create a factory for wrapped C++ objects that can be instantiated and used in JavaScript. ```APIDOC ## Factory Object Creation ### Description This section details the C++ implementation for creating a factory that produces wrapped objects. These objects can be initialized with a value and have a method to retrieve that value. ### Method Signature `static NAN_MODULE_INIT(Init)` ### Usage in JavaScript ```javascript var wrappedobjectfactory = require('bindings')('wrappedobjectfactory'); var obj = wrappedobjectfactory.newFactoryObjectInstance(10); console.log('Should be 10: ' + obj.getValue()); ``` ### C++ Implementation Details - `MyFactoryObject::Init`: Initializes the V8 FunctionTemplate for the object. - `MyFactoryObject::NewInstance`: A static method to create a new instance of `MyFactoryObject`. - `MyFactoryObject::New`: The constructor for `MyFactoryObject`, handling both direct construction and `new` calls. - `MyFactoryObject::GetValue`: A method exposed to JavaScript to get the internal value of the object. - `NODE_MODULE`: Exports the addon with the name 'wrappedobjectfactory'. ``` -------------------------------- ### Define Node Add-on Entry Point with NAN_MODULE_INIT Source: https://github.com/nodejs/nan/blob/main/doc/node_misc.md Use NAN_MODULE_INIT to define the main entry point function for a Node.js add-on. It creates a function that receives a `target` object, similar to JavaScript's `module.exports`. ```c++ NAN_MODULE_INIT(Init) { NAN_EXPORT(target, Foo); } ``` -------------------------------- ### Nan::GetCurrentContext() Source: https://github.com/nodejs/nan/blob/main/doc/v8_misc.md Retrieves the current V8 context. This function provides a consistent way to get the current context across different V8 versions. ```APIDOC ## Nan::GetCurrentContext() ### Description A call to `v8::Isolate::GetCurrent()->GetCurrentContext()` that works across all supported versions of V8. ### Signature ```c++ v8::Local Nan::GetCurrentContext() ``` ``` -------------------------------- ### Script Helpers Source: https://github.com/nodejs/nan/blob/main/README.md NAN provides `v8::Script` helpers as the API has changed over the supported versions of V8. ```APIDOC ## Script Helpers ### `Nan::CompileScript(Local source)` Compiles a JavaScript string into a script. ### `Nan::RunScript(Local