{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"addons","path":"/addons","type":"misc","module":null,"title":"C++ addons","introducedIn":"v0.10.0","sourceLink":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"*Addons* are dynamically-linked shared objects that can be loaded via the\n[`require()`](modules.html#requireid) function as ordinary Node.js modules.\nAddons provide a foreign function interface between JavaScript and native code.\n\nThere are three options for implementing addons:\n\n* [Node-API](n-api.html) (recommended)\n* `nan` ([Native Abstractions for Node.js](https://github.com/nodejs/nan))\n* direct use of internal V8, libuv, and Node.js libraries\n\nThe rest of this document focuses on the latter, requiring\nknowledge of multiple components and APIs:\n\n* [V8](https://v8.dev/): the C++ library Node.js uses to provide the\n  JavaScript implementation. It provides the mechanisms for creating objects,\n  calling functions, etc. The V8's API is documented mostly in the\n  `v8.h` header file (`deps/v8/include/v8.h` in the Node.js source\n  tree), and is also available [online](https://v8docs.nodesource.com/).\n\n* [`libuv`](https://github.com/libuv/libuv): The C library that implements the Node.js event loop, its worker\n  threads and all of the asynchronous behaviors of the platform. It also\n  serves as a cross-platform abstraction library, giving easy, POSIX-like\n  access across all major operating systems to many common system tasks, such\n  as interacting with the file system, sockets, timers, and system events. libuv\n  also provides a threading abstraction similar to POSIX threads for\n  more sophisticated asynchronous addons that need to move beyond the\n  standard event loop. Addon authors should\n  avoid blocking the event loop with I/O or other time-intensive tasks by\n  offloading work via libuv to non-blocking system operations, worker threads,\n  or a custom use of libuv threads.\n\n* Internal Node.js libraries: Node.js itself exports C++ APIs that addons can\n  use, the most important of which is the `node::ObjectWrap` class.\n\n* Other statically linked libraries (including OpenSSL): These\n  other libraries are located in the `deps/` directory in the Node.js source\n  tree. Only the libuv, OpenSSL, V8, and zlib symbols are purposefully\n  re-exported by Node.js and may be used to various extents by addons. See\n  [Linking to libraries included with Node.js](#linking-to-libraries-included-with-nodejs) for additional information.\n\nAll of the following examples are available for [download](https://github.com/nodejs/node-addon-examples) and may\nbe used as the starting-point for an addon.","summary":"_Addons_ are dynamically-linked shared objects that can be loaded via the `require()` function as ordinary Node.js modules. Addons provide a foreign function interface between JavaScript and native code.","examples":[],"children":[{"kind":"section","id":"hello-world","name":"Hello world","title":"Hello world","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"This \"Hello world\" example is a simple addon, written in C++, that is the\nequivalent of the following JavaScript code:\n\n```js\nmodule.exports.hello = () => 'world';\n```\n\nFirst, create the file `hello.cc`:\n\n```cpp\n// hello.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid Method(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid Initialize(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"hello\", Method);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) // N.B.: no semi-colon, this is not a function\n\n}  // namespace demo\n```\n\nOn most platforms, the following `Makefile` can get us started:\n\n```bash\nNODEJS_DEV_ROOT ?= $(shell dirname \"$$(command -v node)\")/..\nCXXFLAGS = -std=c++23 -I$(NODEJS_DEV_ROOT)/include/node -fPIC -shared -Wl,-undefined,dynamic_lookup\n\nhello.node: hello.cc\n\t$(CXX) $(CXXFLAGS) -o $@ $<\n```\n\nThen running the following commands will compile and run the code:\n\n```console\n$ make\n$ node -p 'require(\"./hello.node\").hello()'\nworld\n```\n\nTo integrate with the npm ecosystem, see the [Building](#building) section.","summary":"This \"Hello world\" example is a simple addon, written in C++, that is the equivalent of the following JavaScript code:","examples":[{"language":"js","displayName":null,"code":"module.exports.hello = () => 'world';"},{"language":"cpp","displayName":null,"code":"// hello.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid Method(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid Initialize(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"hello\", Method);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) // N.B.: no semi-colon, this is not a function\n\n}  // namespace demo"},{"language":"bash","displayName":null,"code":"NODEJS_DEV_ROOT ?= $(shell dirname \"$$(command -v node)\")/..\nCXXFLAGS = -std=c++23 -I$(NODEJS_DEV_ROOT)/include/node -fPIC -shared -Wl,-undefined,dynamic_lookup\n\nhello.node: hello.cc\n\t$(CXX) $(CXXFLAGS) -o $@ $<"},{"language":"console","displayName":null,"code":"$ make\n$ node -p 'require(\"./hello.node\").hello()'\nworld"}],"children":[{"kind":"section","id":"context-aware-addons","name":"Context-aware addons","title":"Context-aware addons","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Addons defined with `NODE_MODULE()` cannot be loaded in multiple contexts or\nmultiple threads at the same time.\n\nThere are environments in which Node.js addons may need to be loaded multiple\ntimes in multiple contexts. For example, the [Electron](https://electronjs.org/) runtime runs multiple\ninstances of Node.js in a single process. Each instance will have its own\n`require()` cache, and thus each instance will need a native addon to behave\ncorrectly when loaded via `require()`. This means that the addon\nmust support multiple initializations.\n\nA context-aware addon can be constructed by using the macro\n`NODE_MODULE_INITIALIZER`, which expands to the name of a function which Node.js\nwill expect to find when it loads an addon. An addon can thus be initialized as\nin the following example:\n\n```cpp\nusing namespace v8;\n\nextern \"C\" NODE_MODULE_EXPORT void\nNODE_MODULE_INITIALIZER(Local<Object> exports,\n                        Local<Value> module,\n                        Local<Context> context) {\n  /* Perform addon initialization steps here. */\n}\n```\n\nAnother option is to use the macro `NODE_MODULE_INIT()`, which will also\nconstruct a context-aware addon. Unlike `NODE_MODULE()`, which is used to\nconstruct an addon around a given addon initializer function,\n`NODE_MODULE_INIT()` serves as the declaration of such an initializer to be\nfollowed by a function body.\n\nThe following three variables may be used inside the function body following an\ninvocation of `NODE_MODULE_INIT()`:\n\n* `Local<Object> exports`,\n* `Local<Value> module`, and\n* `Local<Context> context`\n\nBuilding a context-aware addon requires careful management of global static data\nto ensure stability and correctness. Since the addon may be loaded multiple\ntimes, potentially even from different threads, any global static data stored\nin the addon must be properly protected, and must not contain any persistent\nreferences to JavaScript objects. The reason for this is that JavaScript\nobjects are only valid in one context, and will likely cause a crash when\naccessed from the wrong context or from a different thread than the one on which\nthey were created.\n\nThe context-aware addon can be structured to avoid global static data by\nperforming the following steps:\n\n* Define a class which will hold per-addon-instance data and which has a static\n  member of the form\n  ```cpp\n  static void DeleteInstance(void* data) {\n    // Cast `data` to an instance of the class and delete it.\n  }\n  ```\n* Heap-allocate an instance of this class in the addon initializer. This can be\n  accomplished using the `new` keyword.\n* Call `node::AddEnvironmentCleanupHook()`, passing it the above-created\n  instance and a pointer to `DeleteInstance()`. This will ensure the instance is\n  deleted when the environment is torn down.\n* Store the instance of the class in a `v8::External`, and\n* Pass the `v8::External` to all methods exposed to JavaScript by passing it\n  to `v8::FunctionTemplate::New()` or `v8::Function::New()` which creates the\n  native-backed JavaScript functions. The third parameter of\n  `v8::FunctionTemplate::New()` or `v8::Function::New()`  accepts the\n  `v8::External` and makes it available in the native callback using the\n  `v8::FunctionCallbackInfo::Data()` method.\n\nThis will ensure that the per-addon-instance data reaches each binding that can\nbe called from JavaScript. The per-addon-instance data must also be passed into\nany asynchronous callbacks the addon may create.\n\nThe following example illustrates the implementation of a context-aware addon:\n\n```cpp\n#include <node.h>\n\nusing namespace v8;\n\nclass AddonData {\n public:\n  explicit AddonData(Isolate* isolate):\n      call_count(0) {\n    // Ensure this per-addon-instance data is deleted at environment cleanup.\n    node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);\n  }\n\n  // Per-addon data.\n  int call_count;\n\n  static void DeleteInstance(void* data) {\n    delete static_cast<AddonData*>(data);\n  }\n};\n\nstatic void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {\n  // Retrieve the per-addon-instance data.\n  AddonData* data =\n      reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());\n  data->call_count++;\n  info.GetReturnValue().Set((double)data->call_count);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n  Isolate* isolate = Isolate::GetCurrent();\n\n  // Create a new instance of `AddonData` for this instance of the addon and\n  // tie its life cycle to that of the Node.js environment.\n  AddonData* data = new AddonData(isolate);\n\n  // Wrap the data in a `v8::External` so we can pass it to the method we\n  // expose.\n  Local<External> external = External::New(isolate, data);\n\n  // Expose the method `Method` to JavaScript, and make sure it receives the\n  // per-addon-instance data we created above by passing `external` as the\n  // third parameter to the `FunctionTemplate` constructor.\n  exports->Set(context,\n               String::NewFromUtf8(isolate, \"method\").ToLocalChecked(),\n               FunctionTemplate::New(isolate, Method, external)\n                  ->GetFunction(context).ToLocalChecked()).FromJust();\n}\n```","summary":"Addons defined with `NODE_MODULE()` cannot be loaded in multiple contexts or multiple threads at the same time.","examples":[{"language":"cpp","displayName":null,"code":"using namespace v8;\n\nextern \"C\" NODE_MODULE_EXPORT void\nNODE_MODULE_INITIALIZER(Local<Object> exports,\n                        Local<Value> module,\n                        Local<Context> context) {\n  /* Perform addon initialization steps here. */\n}"},{"language":"cpp","displayName":null,"code":"static void DeleteInstance(void* data) {\n  // Cast `data` to an instance of the class and delete it.\n}"},{"language":"cpp","displayName":null,"code":"#include <node.h>\n\nusing namespace v8;\n\nclass AddonData {\n public:\n  explicit AddonData(Isolate* isolate):\n      call_count(0) {\n    // Ensure this per-addon-instance data is deleted at environment cleanup.\n    node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);\n  }\n\n  // Per-addon data.\n  int call_count;\n\n  static void DeleteInstance(void* data) {\n    delete static_cast<AddonData*>(data);\n  }\n};\n\nstatic void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {\n  // Retrieve the per-addon-instance data.\n  AddonData* data =\n      reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());\n  data->call_count++;\n  info.GetReturnValue().Set((double)data->call_count);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n  Isolate* isolate = Isolate::GetCurrent();\n\n  // Create a new instance of `AddonData` for this instance of the addon and\n  // tie its life cycle to that of the Node.js environment.\n  AddonData* data = new AddonData(isolate);\n\n  // Wrap the data in a `v8::External` so we can pass it to the method we\n  // expose.\n  Local<External> external = External::New(isolate, data);\n\n  // Expose the method `Method` to JavaScript, and make sure it receives the\n  // per-addon-instance data we created above by passing `external` as the\n  // third parameter to the `FunctionTemplate` constructor.\n  exports->Set(context,\n               String::NewFromUtf8(isolate, \"method\").ToLocalChecked(),\n               FunctionTemplate::New(isolate, Method, external)\n                  ->GetFunction(context).ToLocalChecked()).FromJust();\n}"}],"children":[{"kind":"section","id":"worker-support","name":"Worker support","title":"Worker support","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v14.8.0","v12.19.0"],"prUrl":"https://github.com/nodejs/node/pull/34572","commit":null,"description":"Cleanup hooks may now be asynchronous."}],"description":"In order to be loaded from multiple Node.js environments,\nsuch as a main thread and a Worker thread, an add-on needs to either:\n\n* Be a [Node-API](n-api.html) addon.\n* Be declared as context-aware using `NODE_MODULE_INIT()` as described above.\n\nIn order to support [`Worker`](worker_threads.html#class-worker) threads, addons need to clean up any resources\nthey may have allocated when such a thread exits. This can be achieved through\nthe usage of the `AddEnvironmentCleanupHook()` function:\n\n```cpp\nvoid AddEnvironmentCleanupHook(v8::Isolate* isolate,\n                               void (*fun)(void* arg),\n                               void* arg);\n```\n\nThis function adds a hook that will run before a given Node.js instance shuts\ndown. If necessary, such hooks can be removed before they are run using\n`RemoveEnvironmentCleanupHook()`, which has the same signature. Callbacks are\nrun in last-in first-out order.\n\nIf necessary, there is an additional pair of `AddEnvironmentCleanupHook()`\nand `RemoveEnvironmentCleanupHook()` overloads, where the cleanup hook takes a\ncallback function. This can be used for shutting down asynchronous resources,\nsuch as any libuv handles registered by the addon.\n\nThe following `addon.cc` uses `AddEnvironmentCleanupHook`:\n\n```cpp\n// addon.cc\n#include <node.h>\n#include <assert.h>\n#include <stdlib.h>\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::HandleScope;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\n\n// Note: In a real-world application, do not rely on static/global data.\nstatic char cookie[] = \"yum yum\";\nstatic int cleanup_cb1_called = 0;\nstatic int cleanup_cb2_called = 0;\n\nstatic void cleanup_cb1(void* arg) {\n  Isolate* isolate = static_cast<Isolate*>(arg);\n  HandleScope scope(isolate);\n  Local<Object> obj = Object::New(isolate);\n  assert(!obj.IsEmpty());  // assert VM is still alive\n  assert(obj->IsObject());\n  cleanup_cb1_called++;\n}\n\nstatic void cleanup_cb2(void* arg) {\n  assert(arg == static_cast<void*>(cookie));\n  cleanup_cb2_called++;\n}\n\nstatic void sanity_check(void*) {\n  assert(cleanup_cb1_called == 1);\n  assert(cleanup_cb2_called == 1);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n  Isolate* isolate = Isolate::GetCurrent();\n\n  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);\n}\n```\n\nTest in JavaScript by running:\n\n```js\n// test.js\nrequire('./build/Release/addon');\n```","summary":"In order to be loaded from multiple Node.js environments, such as a main thread and a Worker thread, an add-on needs to either:","examples":[{"language":"cpp","displayName":null,"code":"void AddEnvironmentCleanupHook(v8::Isolate* isolate,\n                               void (*fun)(void* arg),\n                               void* arg);"},{"language":"cpp","displayName":null,"code":"// addon.cc\n#include <node.h>\n#include <assert.h>\n#include <stdlib.h>\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::HandleScope;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\n\n// Note: In a real-world application, do not rely on static/global data.\nstatic char cookie[] = \"yum yum\";\nstatic int cleanup_cb1_called = 0;\nstatic int cleanup_cb2_called = 0;\n\nstatic void cleanup_cb1(void* arg) {\n  Isolate* isolate = static_cast<Isolate*>(arg);\n  HandleScope scope(isolate);\n  Local<Object> obj = Object::New(isolate);\n  assert(!obj.IsEmpty());  // assert VM is still alive\n  assert(obj->IsObject());\n  cleanup_cb1_called++;\n}\n\nstatic void cleanup_cb2(void* arg) {\n  assert(arg == static_cast<void*>(cookie));\n  cleanup_cb2_called++;\n}\n\nstatic void sanity_check(void*) {\n  assert(cleanup_cb1_called == 1);\n  assert(cleanup_cb2_called == 1);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n  Isolate* isolate = Isolate::GetCurrent();\n\n  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);\n}"},{"language":"js","displayName":null,"code":"// test.js\nrequire('./build/Release/addon');"}],"children":[]}]},{"kind":"section","id":"building","name":"Building","title":"Building","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Once the source code has been written, it must be compiled into the binary\n`addon.node` file. To do so, create a file called `binding.gyp` in the\ntop-level of the project describing the build configuration of the module\nusing a JSON-like format. This file is used by [`node-gyp`](https://github.com/nodejs/node-gyp), a tool written\nspecifically to compile Node.js addons.\n\n```json\n{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"hello.cc\" ]\n    }\n  ]\n}\n```\n\nA version of the `node-gyp` utility is bundled and distributed with\nNode.js as part of `npm`. This version is not made directly available for\ndevelopers to use and is intended only to support the ability to use the\n`npm install` command to compile and install addons. Developers who wish to\nuse `node-gyp` directly can install it using the command\n`npm install -g node-gyp`. See the `node-gyp` [installation instructions](https://github.com/nodejs/node-gyp#installation) for\nmore information, including platform-specific requirements.\n\nOnce the `binding.gyp` file has been created, use `node-gyp configure` to\ngenerate the appropriate project build files for the current platform. This\nwill generate either a `Makefile` (on Unix platforms) or a `vcxproj` file\n(on Windows) in the `build/` directory.\n\nNext, invoke the `node-gyp build` command to generate the compiled `addon.node`\nfile. This will be put into the `build/Release/` directory.\n\nWhen using `npm install` to install a Node.js addon, npm uses its own bundled\nversion of `node-gyp` to perform this same set of actions, generating a\ncompiled version of the addon for the user's platform on demand.\n\nOnce built, the binary addon can be used from within Node.js by pointing\n[`require()`](modules.html#requireid) to the built `addon.node` module:\n\n```js\n// hello.js\nconst addon = require('./build/Release/addon');\n\nconsole.log(addon.hello());\n// Prints: 'world'\n```\n\nBecause the exact path to the compiled addon binary can vary depending on how\nit is compiled (i.e. sometimes it may be in `./build/Debug/`), addons can use\nthe [bindings](https://github.com/TooTallNate/node-bindings) package to load the compiled module.\n\nWhile the `bindings` package implementation is more sophisticated in how it\nlocates addon modules, it is essentially using a `try…catch` pattern similar to:\n\n```js\ntry {\n  return require('./build/Release/addon.node');\n} catch (err) {\n  return require('./build/Debug/addon.node');\n}\n```","summary":"Once the source code has been written, it must be compiled into the binary `addon.node` file. To do so, create a file called `binding.gyp` in the top-level of the project describing the build configuration of the module using a JSON-like format. This file is used by `node-gyp`, a tool written specifically to compile Node.js addons.","examples":[{"language":"json","displayName":null,"code":"{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"hello.cc\" ]\n    }\n  ]\n}"},{"language":"js","displayName":null,"code":"// hello.js\nconst addon = require('./build/Release/addon');\n\nconsole.log(addon.hello());\n// Prints: 'world'"},{"language":"js","displayName":null,"code":"try {\n  return require('./build/Release/addon.node');\n} catch (err) {\n  return require('./build/Debug/addon.node');\n}"}],"children":[]},{"kind":"section","id":"linking-to-libraries-included-with-nodejs","name":"Linking to libraries included with Node.js","title":"Linking to libraries included with Node.js","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Node.js uses statically linked libraries such as V8, libuv, and OpenSSL. All\naddons are required to link to V8 and may link to any of the other dependencies\nas well. Typically, this is as simple as including the appropriate\n`#include <...>` statements (e.g. `#include <v8.h>`) and `node-gyp` will locate\nthe appropriate headers automatically. However, there are a few caveats to be\naware of:\n\n* When `node-gyp` runs, it will detect the specific release version of Node.js\n  and download either the full source tarball or just the headers. If the full\n  source is downloaded, addons will have complete access to the full set of\n  Node.js dependencies. However, if only the Node.js headers are downloaded,\n  then only the symbols exported by Node.js will be available.\n\n* `node-gyp` can be run using the `--nodedir` flag pointing at a local Node.js\n  source image. Using this option, the addon will have access to the full set of\n  dependencies.","summary":"Node.js uses statically linked libraries such as V8, libuv, and OpenSSL. All addons are required to link to V8 and may link to any of the other dependencies as well. Typically, this is as simple as including the appropriate `#include <...>` statements (e.g. `#include <v8.h>`) and `node-gyp` will locate the appropriate headers automatically. However, there are a few caveats to be aware of:","examples":[],"children":[]},{"kind":"section","id":"loading-addons-using-require","name":"Loading addons using require()","title":"Loading addons using `require()`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The filename extension of the compiled addon binary is `.node` (as opposed\nto `.dll` or `.so`). The [`require()`](modules.html#requireid) function is written to look for\nfiles with the `.node` file extension and initialize those as dynamically-linked\nlibraries.\n\nWhen calling [`require()`](modules.html#requireid), the `.node` extension can usually be\nomitted and Node.js will still find and initialize the addon. One caveat,\nhowever, is that Node.js will first attempt to locate and load modules or\nJavaScript files that happen to share the same base name. For instance, if\nthere is a file `addon.js` in the same directory as the binary `addon.node`,\nthen [`require('addon')`](modules.html#requireid) will give precedence to the `addon.js` file\nand load it instead.","summary":"The filename extension of the compiled addon binary is `.node` (as opposed to `.dll` or `.so`). The `require()` function is written to look for files with the `.node` file extension and initialize those as dynamically-linked libraries.","examples":[],"children":[]},{"kind":"section","id":"loading-addons-using-import","name":"Loading addons using import","title":"Loading addons using `import`","scope":"module","overloadOf":null,"stability":{"index":"1.0","description":"Early development"},"added":["v23.6.0","v22.20.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"You can use the [`--experimental-addon-modules`](cli.html#--experimental-addon-modules) flag to enable support for\nboth static `import` and dynamic `import()` to load binary addons.\n\nIf we reuse the Hello World example from earlier, you could do:\n\n```mjs\n// hello.mjs\nimport myAddon from './hello.node';\n// N.B.: import {hello} from './hello.node' would not work\n\nconsole.log(myAddon.hello());\n```\n\n```console\n$ node --experimental-addon-modules hello.mjs\nworld\n```","summary":"You can use the `--experimental-addon-modules` flag to enable support for both static `import` and dynamic `import()` to load binary addons.","examples":[{"language":"mjs","displayName":null,"code":"// hello.mjs\nimport myAddon from './hello.node';\n// N.B.: import {hello} from './hello.node' would not work\n\nconsole.log(myAddon.hello());"},{"language":"console","displayName":null,"code":"$ node --experimental-addon-modules hello.mjs\nworld"}],"children":[]}]},{"kind":"section","id":"native-abstractions-for-nodejs","name":"Native abstractions for Node.js","title":"Native abstractions for Node.js","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Each of the examples illustrated in this document directly use the\nNode.js and V8 APIs for implementing addons. The V8 API can, and has, changed\ndramatically from one V8 release to the next (and one major Node.js release to\nthe next). With each change, addons may need to be updated and recompiled in\norder to continue functioning. The Node.js release schedule is designed to\nminimize the frequency and impact of such changes but there is little that\nNode.js can do to ensure stability of the V8 APIs.\n\nThe [Native Abstractions for Node.js](https://github.com/nodejs/nan) (or `nan`) provide a set of tools that\naddon developers are recommended to use to keep compatibility between past and\nfuture releases of V8 and Node.js. See the `nan` [examples](https://github.com/nodejs/nan/tree/HEAD/examples/) for an\nillustration of how it can be used.","summary":"Each of the examples illustrated in this document directly use the Node.js and V8 APIs for implementing addons. The V8 API can, and has, changed dramatically from one V8 release to the next (and one major Node.js release to the next). With each change, addons may need to be updated and recompiled in order to continue functioning. The Node.js release schedule is designed to minimize the frequency and impact of such changes but there is little that Node.js can do to ensure stability of the V8 APIs.","examples":[],"children":[]},{"kind":"section","id":"node-api","name":"Node-API","title":"Node-API","scope":"module","overloadOf":null,"stability":{"index":"2","description":"Stable"},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"See [C/C++ addons with Node-API](n-api.html).","summary":"See C/C++ addons with Node-API.","examples":[],"children":[]},{"kind":"section","id":"addon-examples","name":"Addon examples","title":"Addon examples","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The following are some example addons intended to help developers get started. The\nexamples use the V8 APIs. Refer to the online [V8 reference](https://v8docs.nodesource.com/)\nfor help with the various V8 calls, and V8's [Embedder's Guide](https://v8.dev/docs/embed) for an\nexplanation of several concepts used such as handles, scopes, function\ntemplates, etc.\n\nEach of these examples uses the following `binding.gyp` file:\n\n```json\n{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"addon.cc\" ]\n    }\n  ]\n}\n```\n\nIn cases where there is more than one `.cc` file, simply add the additional\nfilename to the `sources` array:\n\n```json\n\"sources\": [\"addon.cc\", \"myexample.cc\"]\n```\n\nOnce the `binding.gyp` file is ready, the example addons can be configured and\nbuilt using `node-gyp`:\n\n```bash\nnode-gyp configure build\n```","summary":"The following are some example addons intended to help developers get started. The examples use the V8 APIs. Refer to the online V8 reference for help with the various V8 calls, and V8's Embedder's Guide for an explanation of several concepts used such as handles, scopes, function templates, etc.","examples":[{"language":"json","displayName":null,"code":"{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"addon.cc\" ]\n    }\n  ]\n}"},{"language":"json","displayName":null,"code":"\"sources\": [\"addon.cc\", \"myexample.cc\"]"},{"language":"bash","displayName":null,"code":"node-gyp configure build"}],"children":[{"kind":"section","id":"function-arguments","name":"Function arguments","title":"Function arguments","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Addons will typically expose objects and functions that can be accessed from\nJavaScript running within Node.js. When functions are invoked from JavaScript,\nthe input arguments and return value must be mapped to and from the C/C++\ncode.\n\nThe following example illustrates how to read function arguments passed from\nJavaScript and how to return a result:\n\n```cpp\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Exception;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// This is the implementation of the \"add\" method\n// Input arguments are passed using the\n// const FunctionCallbackInfo<Value>& args struct\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  // Check the number of arguments passed.\n  if (args.Length() < 2) {\n    // Throw an Error that is passed back to JavaScript\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong number of arguments\").ToLocalChecked()));\n    return;\n  }\n\n  // Check the argument types\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong arguments\").ToLocalChecked()));\n    return;\n  }\n\n  // Perform the operation\n  double value =\n      args[0].As<Number>()->Value() + args[1].As<Number>()->Value();\n  Local<Number> num = Number::New(isolate, value);\n\n  // Set the return value (using the passed in\n  // FunctionCallbackInfo<Value>&)\n  args.GetReturnValue().Set(num);\n}\n\nvoid Init(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n```\n\nOnce compiled, the example addon can be required and used from within Node.js:\n\n```js\n// test.js\nconst addon = require('./build/Release/addon');\n\nconsole.log('This should be eight:', addon.add(3, 5));\n```","summary":"Addons will typically expose objects and functions that can be accessed from JavaScript running within Node.js. When functions are invoked from JavaScript, the input arguments and return value must be mapped to and from the C/C++ code.","examples":[{"language":"cpp","displayName":null,"code":"// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Exception;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// This is the implementation of the \"add\" method\n// Input arguments are passed using the\n// const FunctionCallbackInfo<Value>& args struct\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  // Check the number of arguments passed.\n  if (args.Length() < 2) {\n    // Throw an Error that is passed back to JavaScript\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong number of arguments\").ToLocalChecked()));\n    return;\n  }\n\n  // Check the argument types\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong arguments\").ToLocalChecked()));\n    return;\n  }\n\n  // Perform the operation\n  double value =\n      args[0].As<Number>()->Value() + args[1].As<Number>()->Value();\n  Local<Number> num = Number::New(isolate, value);\n\n  // Set the return value (using the passed in\n  // FunctionCallbackInfo<Value>&)\n  args.GetReturnValue().Set(num);\n}\n\nvoid Init(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo"},{"language":"js","displayName":null,"code":"// test.js\nconst addon = require('./build/Release/addon');\n\nconsole.log('This should be eight:', addon.add(3, 5));"}],"children":[]},{"kind":"section","id":"callbacks","name":"Callbacks","title":"Callbacks","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"It is common practice within addons to pass JavaScript functions to a C++\nfunction and execute them from there. The following example illustrates how\nto invoke such callbacks:\n\n```cpp\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Null;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid RunCallback(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = {\n      String::NewFromUtf8(isolate,\n                          \"hello world\").ToLocalChecked() };\n  cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", RunCallback);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n```\n\nThis example uses a two-argument form of `Init()` that receives the full\n`module` object as the second argument. This allows the addon to completely\noverwrite `exports` with a single function instead of adding the function as a\nproperty of `exports`.\n\nTo test it, run the following JavaScript:\n\n```js\n// test.js\nconst addon = require('./build/Release/addon');\n\naddon((msg) => {\n  console.log(msg);\n// Prints: 'hello world'\n});\n```\n\nIn this example, the callback function is invoked synchronously.","summary":"It is common practice within addons to pass JavaScript functions to a C++ function and execute them from there. The following example illustrates how to invoke such callbacks:","examples":[{"language":"cpp","displayName":null,"code":"// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Null;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid RunCallback(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = {\n      String::NewFromUtf8(isolate,\n                          \"hello world\").ToLocalChecked() };\n  cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", RunCallback);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo"},{"language":"js","displayName":null,"code":"// test.js\nconst addon = require('./build/Release/addon');\n\naddon((msg) => {\n  console.log(msg);\n// Prints: 'hello world'\n});"}],"children":[]},{"kind":"section","id":"object-factory","name":"Object factory","title":"Object factory","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Addons can create and return new objects from within a C++ function as\nillustrated in the following example. An object is created and returned with a\nproperty `msg` that echoes the string passed to `createObject()`:\n\n```cpp\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  Local<Object> obj = Object::New(isolate);\n  obj->Set(context,\n           String::NewFromUtf8(isolate,\n                               \"msg\").ToLocalChecked(),\n                               args[0]->ToString(context).ToLocalChecked())\n           .FromJust();\n\n  args.GetReturnValue().Set(obj);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n```\n\nTo test it in JavaScript:\n\n```js\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon('hello');\nconst obj2 = addon('world');\nconsole.log(obj1.msg, obj2.msg);\n// Prints: 'hello world'\n```","summary":"Addons can create and return new objects from within a C++ function as illustrated in the following example. An object is created and returned with a property `msg` that echoes the string passed to `createObject()`:","examples":[{"language":"cpp","displayName":null,"code":"// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  Local<Object> obj = Object::New(isolate);\n  obj->Set(context,\n           String::NewFromUtf8(isolate,\n                               \"msg\").ToLocalChecked(),\n                               args[0]->ToString(context).ToLocalChecked())\n           .FromJust();\n\n  args.GetReturnValue().Set(obj);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo"},{"language":"js","displayName":null,"code":"// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon('hello');\nconst obj2 = addon('world');\nconsole.log(obj1.msg, obj2.msg);\n// Prints: 'hello world'"}],"children":[]},{"kind":"section","id":"function-factory","name":"Function factory","title":"Function factory","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Another common scenario is creating JavaScript functions that wrap C++\nfunctions and returning those back to JavaScript:\n\n```cpp\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid MyFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"hello world\").ToLocalChecked());\n}\n\nvoid CreateFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);\n  Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();\n\n  // omit this to make it anonymous\n  fn->SetName(String::NewFromUtf8(\n      isolate, \"theFunction\").ToLocalChecked());\n\n  args.GetReturnValue().Set(fn);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateFunction);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n```\n\nTo test:\n\n```js\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst fn = addon();\nconsole.log(fn());\n// Prints: 'hello world'\n```","summary":"Another common scenario is creating JavaScript functions that wrap C++ functions and returning those back to JavaScript:","examples":[{"language":"cpp","displayName":null,"code":"// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid MyFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"hello world\").ToLocalChecked());\n}\n\nvoid CreateFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);\n  Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();\n\n  // omit this to make it anonymous\n  fn->SetName(String::NewFromUtf8(\n      isolate, \"theFunction\").ToLocalChecked());\n\n  args.GetReturnValue().Set(fn);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateFunction);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo"},{"language":"js","displayName":null,"code":"// test.js\nconst addon = require('./build/Release/addon');\n\nconst fn = addon();\nconsole.log(fn());\n// Prints: 'hello world'"}],"children":[]},{"kind":"section","id":"wrapping-c-objects","name":"Wrapping C++ objects","title":"Wrapping C++ objects","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"It is also possible to wrap C++ objects/classes in a way that allows new\ninstances to be created using the JavaScript `new` operator:\n\n```cpp\n// addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Local;\nusing v8::Object;\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init(exports);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n```\n\nThen, in `myobject.h`, the wrapper class inherits from `node::ObjectWrap`:\n\n```cpp\n// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Local<v8::Object> exports);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n```\n\nIn `myobject.cc`, implement the various methods that are to be exposed.\nIn the following code, the method `plusOne()` is exposed by adding it to the\nconstructor's prototype:\n\n```cpp\n// myobject.cc\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::String;\nusing v8::Value;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Local<Object> exports) {\n  Isolate* isolate = Isolate::GetCurrent();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);\n  addon_data_tpl->SetInternalFieldCount(1);  // 1 field for the MyObject::New()\n  Local<Object> addon_data =\n      addon_data_tpl->NewInstance(context).ToLocalChecked();\n\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New, addon_data);\n  tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Function> constructor = tpl->GetFunction(context).ToLocalChecked();\n  addon_data->SetInternalField(0, constructor);\n  exports->Set(context, String::NewFromUtf8(\n      isolate, \"MyObject\").ToLocalChecked(),\n      constructor).FromJust();\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons =\n        args.Data().As<Object>()->GetInternalField(0)\n            .As<Value>().As<Function>();\n    Local<Object> result =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(result);\n  }\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n```\n\nTo build this example, the `myobject.cc` file must be added to the\n`binding.gyp`:\n\n```json\n{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n```\n\nTest it with:\n\n```js\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj = new addon.MyObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n```\n\nThe destructor for a wrapper object will run when the object is\ngarbage-collected. For destructor testing, there are command-line flags that\ncan be used to make it possible to force garbage collection. These flags are\nprovided by the underlying V8 JavaScript engine. They are subject to change\nor removal at any time. They are not documented by Node.js or V8, and they\nshould never be used outside of testing.\n\nDuring shutdown of the process or worker threads, destructors are not called\nby the JS engine. Therefore it's the responsibility of the user to track\nthese objects and ensure proper destruction to avoid resource leaks.","summary":"It is also possible to wrap C++ objects/classes in a way that allows new instances to be created using the JavaScript `new` operator:","examples":[{"language":"cpp","displayName":null,"code":"// addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Local;\nusing v8::Object;\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init(exports);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo"},{"language":"cpp","displayName":null,"code":"// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Local<v8::Object> exports);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n  double value_;\n};\n\n}  // namespace demo\n\n#endif"},{"language":"cpp","displayName":null,"code":"// myobject.cc\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::String;\nusing v8::Value;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Local<Object> exports) {\n  Isolate* isolate = Isolate::GetCurrent();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);\n  addon_data_tpl->SetInternalFieldCount(1);  // 1 field for the MyObject::New()\n  Local<Object> addon_data =\n      addon_data_tpl->NewInstance(context).ToLocalChecked();\n\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New, addon_data);\n  tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Function> constructor = tpl->GetFunction(context).ToLocalChecked();\n  addon_data->SetInternalField(0, constructor);\n  exports->Set(context, String::NewFromUtf8(\n      isolate, \"MyObject\").ToLocalChecked(),\n      constructor).FromJust();\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons =\n        args.Data().As<Object>()->GetInternalField(0)\n            .As<Value>().As<Function>();\n    Local<Object> result =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(result);\n  }\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo"},{"language":"json","displayName":null,"code":"{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}"},{"language":"js","displayName":null,"code":"// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj = new addon.MyObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13"}],"children":[]},{"kind":"section","id":"factory-of-wrapped-objects","name":"Factory of wrapped objects","title":"Factory of wrapped objects","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Alternatively, it is possible to use a factory pattern to avoid explicitly\ncreating object instances using the JavaScript `new` operator:\n\n```js\nconst obj = addon.createObject();\n// instead of:\n// const obj = new addon.Object();\n```\n\nFirst, the `createObject()` method is implemented in `addon.cc`:\n\n```cpp\n// addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid InitAll(Local<Object> exports, Local<Object> module) {\n  MyObject::Init();\n\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n```\n\nIn `myobject.h`, the static method `NewInstance()` is added to handle\ninstantiating the object. This method takes the place of using `new` in\nJavaScript:\n\n```cpp\n// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Global<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n```\n\nThe implementation in `myobject.cc` is similar to the previous example:\n\n```cpp\n// myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  Isolate* isolate = Isolate::GetCurrent();\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n  AddEnvironmentCleanupHook(isolate, [](void*) {\n    constructor.Reset();\n  }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n```\n\nOnce again, to build this example, the `myobject.cc` file must be added to the\n`binding.gyp`:\n\n```json\n{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n```\n\nTest it with:\n\n```js\n// test.js\nconst createObject = require('./build/Release/addon');\n\nconst obj = createObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n\nconst obj2 = createObject(20);\nconsole.log(obj2.plusOne());\n// Prints: 21\nconsole.log(obj2.plusOne());\n// Prints: 22\nconsole.log(obj2.plusOne());\n// Prints: 23\n```","summary":"Alternatively, it is possible to use a factory pattern to avoid explicitly creating object instances using the JavaScript `new` operator:","examples":[{"language":"js","displayName":null,"code":"const obj = addon.createObject();\n// instead of:\n// const obj = new addon.Object();"},{"language":"cpp","displayName":null,"code":"// addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid InitAll(Local<Object> exports, Local<Object> module) {\n  MyObject::Init();\n\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo"},{"language":"cpp","displayName":null,"code":"// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Global<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif"},{"language":"cpp","displayName":null,"code":"// myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  Isolate* isolate = Isolate::GetCurrent();\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n  AddEnvironmentCleanupHook(isolate, [](void*) {\n    constructor.Reset();\n  }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo"},{"language":"json","displayName":null,"code":"{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}"},{"language":"js","displayName":null,"code":"// test.js\nconst createObject = require('./build/Release/addon');\n\nconst obj = createObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n\nconst obj2 = createObject(20);\nconsole.log(obj2.plusOne());\n// Prints: 21\nconsole.log(obj2.plusOne());\n// Prints: 22\nconsole.log(obj2.plusOne());\n// Prints: 23"}],"children":[]},{"kind":"section","id":"passing-wrapped-objects-around","name":"Passing wrapped objects around","title":"Passing wrapped objects around","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"In addition to wrapping and returning C++ objects, it is possible to pass\nwrapped objects around by unwrapping them with the Node.js helper function\n`node::ObjectWrap::Unwrap`. The following example shows a function `add()`\nthat can take two `MyObject` objects as input arguments:\n\n```cpp\n// addon.cc\n#include <node.h>\n#include <node_object_wrap.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject(context).ToLocalChecked());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject(context).ToLocalChecked());\n\n  double sum = obj1->value() + obj2->value();\n  args.GetReturnValue().Set(Number::New(isolate, sum));\n}\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init();\n\n  NODE_SET_METHOD(exports, \"createObject\", CreateObject);\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n```\n\nIn `myobject.h`, a new public method is added to allow access to private values\nafter unwrapping the object.\n\n```cpp\n// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n  inline double value() const { return value_; }\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Global<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n```\n\nThe implementation of `myobject.cc` remains similar to the previous version:\n\n```cpp\n// myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  Isolate* isolate = Isolate::GetCurrent();\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n  AddEnvironmentCleanupHook(isolate, [](void*) {\n    constructor.Reset();\n  }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\n}  // namespace demo\n```\n\nTest it with:\n\n```js\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon.createObject(10);\nconst obj2 = addon.createObject(20);\nconst result = addon.add(obj1, obj2);\n\nconsole.log(result);\n// Prints: 30\n```","summary":"In addition to wrapping and returning C++ objects, it is possible to pass wrapped objects around by unwrapping them with the Node.js helper function `node::ObjectWrap::Unwrap`. The following example shows a function `add()` that can take two `MyObject` objects as input arguments:","examples":[{"language":"cpp","displayName":null,"code":"// addon.cc\n#include <node.h>\n#include <node_object_wrap.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject(context).ToLocalChecked());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject(context).ToLocalChecked());\n\n  double sum = obj1->value() + obj2->value();\n  args.GetReturnValue().Set(Number::New(isolate, sum));\n}\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init();\n\n  NODE_SET_METHOD(exports, \"createObject\", CreateObject);\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo"},{"language":"cpp","displayName":null,"code":"// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n  inline double value() const { return value_; }\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Global<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif"},{"language":"cpp","displayName":null,"code":"// myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  Isolate* isolate = Isolate::GetCurrent();\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n  AddEnvironmentCleanupHook(isolate, [](void*) {\n    constructor.Reset();\n  }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\n}  // namespace demo"},{"language":"js","displayName":null,"code":"// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon.createObject(10);\nconst obj2 = addon.createObject(20);\nconst result = addon.add(obj1, obj2);\n\nconsole.log(result);\n// Prints: 30"}],"children":[]}]}]}