{
  "type": "module",
  "source": "doc/api/addons.md",
  "introduced_in": "v0.10.0",
  "miscs": [
    {
      "textRaw": "C++ addons",
      "name": "C++ addons",
      "introduced_in": "v0.10.0",
      "type": "misc",
      "desc": "<p><em>Addons</em> are dynamically-linked shared objects that can be loaded via the\n<a href=\"modules.html#requireid\"><code>require()</code></a> function as ordinary Node.js modules.\nAddons provide a foreign function interface between JavaScript and native code.</p>\n<p>There are three options for implementing addons:</p>\n<ul>\n<li><a href=\"n-api.html\">Node-API</a> (recommended)</li>\n<li><code>nan</code> (<a href=\"https://github.com/nodejs/nan\">Native Abstractions for Node.js</a>)</li>\n<li>direct use of internal V8, libuv, and Node.js libraries</li>\n</ul>\n<p>This rest of this document focuses on the latter, requiring\nknowledge of multiple components and APIs:</p>\n<ul>\n<li>\n<p><a href=\"https://v8.dev/\">V8</a>: the C++ library Node.js uses to provide the\nJavaScript implementation. It provides the mechanisms for creating objects,\ncalling functions, etc. The V8's API is documented mostly in the\n<code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node.js source\ntree), and is also available <a href=\"https://v8docs.nodesource.com/\">online</a>.</p>\n</li>\n<li>\n<p><a href=\"https://github.com/libuv/libuv\"><code>libuv</code></a>: The C library that implements the Node.js event loop, its worker\nthreads and all of the asynchronous behaviors of the platform. It also\nserves as a cross-platform abstraction library, giving easy, POSIX-like\naccess across all major operating systems to many common system tasks, such\nas interacting with the file system, sockets, timers, and system events. libuv\nalso provides a threading abstraction similar to POSIX threads for\nmore sophisticated asynchronous addons that need to move beyond the\nstandard event loop. Addon authors should\navoid blocking the event loop with I/O or other time-intensive tasks by\noffloading work via libuv to non-blocking system operations, worker threads,\nor a custom use of libuv threads.</p>\n</li>\n<li>\n<p>Internal Node.js libraries: Node.js itself exports C++ APIs that addons can\nuse, the most important of which is the <code>node::ObjectWrap</code> class.</p>\n</li>\n<li>\n<p>Other statically linked libraries (including OpenSSL): These\nother libraries are located in the <code>deps/</code> directory in the Node.js source\ntree. Only the libuv, OpenSSL, V8, and zlib symbols are purposefully\nre-exported by Node.js and may be used to various extents by addons. See\n<a href=\"#linking-to-libraries-included-with-nodejs\">Linking to libraries included with Node.js</a> for additional information.</p>\n</li>\n</ul>\n<p>All of the following examples are available for <a href=\"https://github.com/nodejs/node-addon-examples\">download</a> and may\nbe used as the starting-point for an addon.</p>",
      "miscs": [
        {
          "textRaw": "Hello world",
          "name": "hello_world",
          "type": "misc",
          "desc": "<p>This \"Hello world\" example is a simple addon, written in C++, that is the\nequivalent of the following JavaScript code:</p>\n<pre><code class=\"language-js\">module.exports.hello = () => 'world';\n</code></pre>\n<p>First, create the file <code>hello.cc</code>:</p>\n<pre><code class=\"language-cpp\">// hello.cc\n#include &#x3C;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&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid Initialize(Local&#x3C;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</code></pre>\n<p>On most platforms, the following <code>Makefile</code> can get us started:</p>\n<pre><code class=\"language-bash\">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 $@ $&#x3C;\n</code></pre>\n<p>Then running the following commands will compile and run the code:</p>\n<pre><code class=\"language-console\">$ make\n$ node -p 'require(\"./hello.node\").hello()'\nworld\n</code></pre>\n<p>To integrate with the npm ecosystem, see the <a href=\"#building\">Building</a> section.</p>",
          "modules": [
            {
              "textRaw": "Context-aware addons",
              "name": "context-aware_addons",
              "type": "module",
              "desc": "<p>Addons defined with <code>NODE_MODULE()</code> can not be loaded in multiple contexts or\nmultiple threads at the same time.</p>\n<p>There are environments in which Node.js addons may need to be loaded multiple\ntimes in multiple contexts. For example, the <a href=\"https://electronjs.org/\">Electron</a> runtime runs multiple\ninstances of Node.js in a single process. Each instance will have its own\n<code>require()</code> cache, and thus each instance will need a native addon to behave\ncorrectly when loaded via <code>require()</code>. This means that the addon\nmust support multiple initializations.</p>\n<p>A context-aware addon can be constructed by using the macro\n<code>NODE_MODULE_INITIALIZER</code>, 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:</p>\n<pre><code class=\"language-cpp\">using namespace v8;\n\nextern \"C\" NODE_MODULE_EXPORT void\nNODE_MODULE_INITIALIZER(Local&#x3C;Object> exports,\n                        Local&#x3C;Value> module,\n                        Local&#x3C;Context> context) {\n  /* Perform addon initialization steps here. */\n}\n</code></pre>\n<p>Another option is to use the macro <code>NODE_MODULE_INIT()</code>, which will also\nconstruct a context-aware addon. Unlike <code>NODE_MODULE()</code>, which is used to\nconstruct an addon around a given addon initializer function,\n<code>NODE_MODULE_INIT()</code> serves as the declaration of such an initializer to be\nfollowed by a function body.</p>\n<p>The following three variables may be used inside the function body following an\ninvocation of <code>NODE_MODULE_INIT()</code>:</p>\n<ul>\n<li><code>Local&#x3C;Object> exports</code>,</li>\n<li><code>Local&#x3C;Value> module</code>, and</li>\n<li><code>Local&#x3C;Context> context</code></li>\n</ul>\n<p>Building 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.</p>\n<p>The context-aware addon can be structured to avoid global static data by\nperforming the following steps:</p>\n<ul>\n<li>Define a class which will hold per-addon-instance data and which has a static\nmember of the form\n<pre><code class=\"language-cpp\">static void DeleteInstance(void* data) {\n  // Cast `data` to an instance of the class and delete it.\n}\n</code></pre>\n</li>\n<li>Heap-allocate an instance of this class in the addon initializer. This can be\naccomplished using the <code>new</code> keyword.</li>\n<li>Call <code>node::AddEnvironmentCleanupHook()</code>, passing it the above-created\ninstance and a pointer to <code>DeleteInstance()</code>. This will ensure the instance is\ndeleted when the environment is torn down.</li>\n<li>Store the instance of the class in a <code>v8::External</code>, and</li>\n<li>Pass the <code>v8::External</code> to all methods exposed to JavaScript by passing it\nto <code>v8::FunctionTemplate::New()</code> or <code>v8::Function::New()</code> which creates the\nnative-backed JavaScript functions. The third parameter of\n<code>v8::FunctionTemplate::New()</code> or <code>v8::Function::New()</code>  accepts the\n<code>v8::External</code> and makes it available in the native callback using the\n<code>v8::FunctionCallbackInfo::Data()</code> method.</li>\n</ul>\n<p>This 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.</p>\n<p>The following example illustrates the implementation of a context-aware addon:</p>\n<pre><code class=\"language-cpp\">#include &#x3C;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&#x3C;AddonData*>(data);\n  }\n};\n\nstatic void Method(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; info) {\n  // Retrieve the per-addon-instance data.\n  AddonData* data =\n      reinterpret_cast&#x3C;AddonData*>(info.Data().As&#x3C;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&#x3C;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</code></pre>",
              "modules": [
                {
                  "textRaw": "Worker support",
                  "name": "worker_support",
                  "type": "module",
                  "meta": {
                    "changes": [
                      {
                        "version": [
                          "v14.8.0",
                          "v12.19.0"
                        ],
                        "pr-url": "https://github.com/nodejs/node/pull/34572",
                        "description": "Cleanup hooks may now be asynchronous."
                      }
                    ]
                  },
                  "desc": "<p>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:</p>\n<ul>\n<li>Be an <a href=\"n-api.html\">Node-API</a> addon.</li>\n<li>Be declared as context-aware using <code>NODE_MODULE_INIT()</code> as described above.</li>\n</ul>\n<p>In order to support <a href=\"worker_threads.html#class-worker\"><code>Worker</code></a> 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 <code>AddEnvironmentCleanupHook()</code> function:</p>\n<pre><code class=\"language-cpp\">void AddEnvironmentCleanupHook(v8::Isolate* isolate,\n                               void (*fun)(void* arg),\n                               void* arg);\n</code></pre>\n<p>This 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<code>RemoveEnvironmentCleanupHook()</code>, which has the same signature. Callbacks are\nrun in last-in first-out order.</p>\n<p>If necessary, there is an additional pair of <code>AddEnvironmentCleanupHook()</code>\nand <code>RemoveEnvironmentCleanupHook()</code> 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.</p>\n<p>The following <code>addon.cc</code> uses <code>AddEnvironmentCleanupHook</code>:</p>\n<pre><code class=\"language-cpp\">// addon.cc\n#include &#x3C;node.h>\n#include &#x3C;assert.h>\n#include &#x3C;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&#x3C;Isolate*>(arg);\n  HandleScope scope(isolate);\n  Local&#x3C;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&#x3C;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</code></pre>\n<p>Test in JavaScript by running:</p>\n<pre><code class=\"language-js\">// test.js\nrequire('./build/Release/addon');\n</code></pre>",
                  "displayName": "Worker support"
                }
              ],
              "displayName": "Context-aware addons"
            },
            {
              "textRaw": "Building",
              "name": "building",
              "type": "module",
              "desc": "<p>Once the source code has been written, it must be compiled into the binary\n<code>addon.node</code> file. To do so, create a file called <code>binding.gyp</code> in the\ntop-level of the project describing the build configuration of the module\nusing a JSON-like format. This file is used by <a href=\"https://github.com/nodejs/node-gyp\"><code>node-gyp</code></a>, a tool written\nspecifically to compile Node.js addons.</p>\n<pre><code class=\"language-json\">{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"hello.cc\" ]\n    }\n  ]\n}\n</code></pre>\n<p>A version of the <code>node-gyp</code> utility is bundled and distributed with\nNode.js as part of <code>npm</code>. This version is not made directly available for\ndevelopers to use and is intended only to support the ability to use the\n<code>npm install</code> command to compile and install addons. Developers who wish to\nuse <code>node-gyp</code> directly can install it using the command\n<code>npm install -g node-gyp</code>. See the <code>node-gyp</code> <a href=\"https://github.com/nodejs/node-gyp#installation\">installation instructions</a> for\nmore information, including platform-specific requirements.</p>\n<p>Once the <code>binding.gyp</code> file has been created, use <code>node-gyp configure</code> to\ngenerate the appropriate project build files for the current platform. This\nwill generate either a <code>Makefile</code> (on Unix platforms) or a <code>vcxproj</code> file\n(on Windows) in the <code>build/</code> directory.</p>\n<p>Next, invoke the <code>node-gyp build</code> command to generate the compiled <code>addon.node</code>\nfile. This will be put into the <code>build/Release/</code> directory.</p>\n<p>When using <code>npm install</code> to install a Node.js addon, npm uses its own bundled\nversion of <code>node-gyp</code> to perform this same set of actions, generating a\ncompiled version of the addon for the user's platform on demand.</p>\n<p>Once built, the binary addon can be used from within Node.js by pointing\n<a href=\"modules.html#requireid\"><code>require()</code></a> to the built <code>addon.node</code> module:</p>\n<pre><code class=\"language-js\">// hello.js\nconst addon = require('./build/Release/addon');\n\nconsole.log(addon.hello());\n// Prints: 'world'\n</code></pre>\n<p>Because the exact path to the compiled addon binary can vary depending on how\nit is compiled (i.e. sometimes it may be in <code>./build/Debug/</code>), addons can use\nthe <a href=\"https://github.com/TooTallNate/node-bindings\">bindings</a> package to load the compiled module.</p>\n<p>While the <code>bindings</code> package implementation is more sophisticated in how it\nlocates addon modules, it is essentially using a <code>try…catch</code> pattern similar to:</p>\n<pre><code class=\"language-js\">try {\n  return require('./build/Release/addon.node');\n} catch (err) {\n  return require('./build/Debug/addon.node');\n}\n</code></pre>",
              "displayName": "Building"
            },
            {
              "textRaw": "Linking to libraries included with Node.js",
              "name": "linking_to_libraries_included_with_node.js",
              "type": "module",
              "desc": "<p>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<code>#include &#x3C;...></code> statements (e.g. <code>#include &#x3C;v8.h></code>) and <code>node-gyp</code> will locate\nthe appropriate headers automatically. However, there are a few caveats to be\naware of:</p>\n<ul>\n<li>\n<p>When <code>node-gyp</code> runs, it will detect the specific release version of Node.js\nand download either the full source tarball or just the headers. If the full\nsource is downloaded, addons will have complete access to the full set of\nNode.js dependencies. However, if only the Node.js headers are downloaded,\nthen only the symbols exported by Node.js will be available.</p>\n</li>\n<li>\n<p><code>node-gyp</code> can be run using the <code>--nodedir</code> flag pointing at a local Node.js\nsource image. Using this option, the addon will have access to the full set of\ndependencies.</p>\n</li>\n</ul>",
              "displayName": "Linking to libraries included with Node.js"
            },
            {
              "textRaw": "Loading addons using `require()`",
              "name": "loading_addons_using_`require()`",
              "type": "module",
              "desc": "<p>The filename extension of the compiled addon binary is <code>.node</code> (as opposed\nto <code>.dll</code> or <code>.so</code>). The <a href=\"modules.html#requireid\"><code>require()</code></a> function is written to look for\nfiles with the <code>.node</code> file extension and initialize those as dynamically-linked\nlibraries.</p>\n<p>When calling <a href=\"modules.html#requireid\"><code>require()</code></a>, the <code>.node</code> 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 <code>addon.js</code> in the same directory as the binary <code>addon.node</code>,\nthen <a href=\"modules.html#requireid\"><code>require('addon')</code></a> will give precedence to the <code>addon.js</code> file\nand load it instead.</p>",
              "displayName": "Loading addons using `require()`"
            },
            {
              "textRaw": "Loading addons using `import`",
              "name": "loading_addons_using_`import`",
              "type": "module",
              "meta": {
                "added": [
                  "v23.6.0",
                  "v22.20.0"
                ],
                "changes": []
              },
              "stability": 1,
              "stabilityText": "Early development",
              "desc": "<p>You can use the <a href=\"cli.html#--experimental-addon-modules\"><code>--experimental-addon-modules</code></a> flag to enable support for\nboth static <code>import</code> and dynamic <code>import()</code> to load binary addons.</p>\n<p>If we reuse the Hello World example from earlier, you could do:</p>\n<pre><code class=\"language-mjs\">// hello.mjs\nimport myAddon from './hello.node';\n// N.B.: import {hello} from './hello.node' would not work\n\nconsole.log(myAddon.hello());\n</code></pre>\n<pre><code class=\"language-console\">$ node --experimental-addon-modules hello.mjs\nworld\n</code></pre>",
              "displayName": "Loading addons using `import`"
            }
          ],
          "displayName": "Hello world"
        },
        {
          "textRaw": "Native abstractions for Node.js",
          "name": "native_abstractions_for_node.js",
          "type": "misc",
          "desc": "<p>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.</p>\n<p>The <a href=\"https://github.com/nodejs/nan\">Native Abstractions for Node.js</a> (or <code>nan</code>) 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 <code>nan</code> <a href=\"https://github.com/nodejs/nan/tree/HEAD/examples/\">examples</a> for an\nillustration of how it can be used.</p>",
          "displayName": "Native abstractions for Node.js"
        },
        {
          "textRaw": "Node-API",
          "name": "node-api",
          "type": "misc",
          "stability": 2,
          "stabilityText": "Stable",
          "desc": "<p>See <a href=\"n-api.html\">C/C++ addons with Node-API</a>.</p>",
          "displayName": "Node-API"
        },
        {
          "textRaw": "Addon examples",
          "name": "addon_examples",
          "type": "misc",
          "desc": "<p>Following are some example addons intended to help developers get started. The\nexamples use the V8 APIs. Refer to the online <a href=\"https://v8docs.nodesource.com/\">V8 reference</a>\nfor help with the various V8 calls, and V8's <a href=\"https://v8.dev/docs/embed\">Embedder's Guide</a> for an\nexplanation of several concepts used such as handles, scopes, function\ntemplates, etc.</p>\n<p>Each of these examples using the following <code>binding.gyp</code> file:</p>\n<pre><code class=\"language-json\">{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"addon.cc\" ]\n    }\n  ]\n}\n</code></pre>\n<p>In cases where there is more than one <code>.cc</code> file, simply add the additional\nfilename to the <code>sources</code> array:</p>\n<pre><code class=\"language-json\">\"sources\": [\"addon.cc\", \"myexample.cc\"]\n</code></pre>\n<p>Once the <code>binding.gyp</code> file is ready, the example addons can be configured and\nbuilt using <code>node-gyp</code>:</p>\n<pre><code class=\"language-bash\">node-gyp configure build\n</code></pre>",
          "modules": [
            {
              "textRaw": "Function arguments",
              "name": "function_arguments",
              "type": "module",
              "desc": "<p>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.</p>\n<p>The following example illustrates how to read function arguments passed from\nJavaScript and how to return a result:</p>\n<pre><code class=\"language-cpp\">// addon.cc\n#include &#x3C;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&#x3C;Value>&#x26; args struct\nvoid Add(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n\n  // Check the number of arguments passed.\n  if (args.Length() &#x3C; 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&#x3C;Number>()->Value() + args[1].As&#x3C;Number>()->Value();\n  Local&#x3C;Number> num = Number::New(isolate, value);\n\n  // Set the return value (using the passed in\n  // FunctionCallbackInfo&#x3C;Value>&#x26;)\n  args.GetReturnValue().Set(num);\n}\n\nvoid Init(Local&#x3C;Object> exports) {\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n</code></pre>\n<p>Once compiled, the example addon can be required and used from within Node.js:</p>\n<pre><code class=\"language-js\">// test.js\nconst addon = require('./build/Release/addon');\n\nconsole.log('This should be eight:', addon.add(3, 5));\n</code></pre>",
              "displayName": "Function arguments"
            },
            {
              "textRaw": "Callbacks",
              "name": "callbacks",
              "type": "module",
              "desc": "<p>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:</p>\n<pre><code class=\"language-cpp\">// addon.cc\n#include &#x3C;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&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n  Local&#x3C;Context> context = isolate->GetCurrentContext();\n  Local&#x3C;Function> cb = Local&#x3C;Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local&#x3C;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&#x3C;Object> exports, Local&#x3C;Object> module) {\n  NODE_SET_METHOD(module, \"exports\", RunCallback);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n</code></pre>\n<p>This example uses a two-argument form of <code>Init()</code> that receives the full\n<code>module</code> object as the second argument. This allows the addon to completely\noverwrite <code>exports</code> with a single function instead of adding the function as a\nproperty of <code>exports</code>.</p>\n<p>To test it, run the following JavaScript:</p>\n<pre><code class=\"language-js\">// test.js\nconst addon = require('./build/Release/addon');\n\naddon((msg) => {\n  console.log(msg);\n// Prints: 'hello world'\n});\n</code></pre>\n<p>In this example, the callback function is invoked synchronously.</p>",
              "displayName": "Callbacks"
            },
            {
              "textRaw": "Object factory",
              "name": "object_factory",
              "type": "module",
              "desc": "<p>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 <code>msg</code> that echoes the string passed to <code>createObject()</code>:</p>\n<pre><code class=\"language-cpp\">// addon.cc\n#include &#x3C;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&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n  Local&#x3C;Context> context = isolate->GetCurrentContext();\n\n  Local&#x3C;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&#x3C;Object> exports, Local&#x3C;Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n</code></pre>\n<p>To test it in JavaScript:</p>\n<pre><code class=\"language-js\">// 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</code></pre>",
              "displayName": "Object factory"
            },
            {
              "textRaw": "Function factory",
              "name": "function_factory",
              "type": "module",
              "desc": "<p>Another common scenario is creating JavaScript functions that wrap C++\nfunctions and returning those back to JavaScript:</p>\n<pre><code class=\"language-cpp\">// addon.cc\n#include &#x3C;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&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"hello world\").ToLocalChecked());\n}\n\nvoid CreateFunction(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n\n  Local&#x3C;Context> context = isolate->GetCurrentContext();\n  Local&#x3C;FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);\n  Local&#x3C;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&#x3C;Object> exports, Local&#x3C;Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateFunction);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n</code></pre>\n<p>To test:</p>\n<pre><code class=\"language-js\">// test.js\nconst addon = require('./build/Release/addon');\n\nconst fn = addon();\nconsole.log(fn());\n// Prints: 'hello world'\n</code></pre>",
              "displayName": "Function factory"
            },
            {
              "textRaw": "Wrapping C++ objects",
              "name": "wrapping_c++_objects",
              "type": "module",
              "desc": "<p>It is also possible to wrap C++ objects/classes in a way that allows new\ninstances to be created using the JavaScript <code>new</code> operator:</p>\n<pre><code class=\"language-cpp\">// addon.cc\n#include &#x3C;node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Local;\nusing v8::Object;\n\nvoid InitAll(Local&#x3C;Object> exports) {\n  MyObject::Init(exports);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n</code></pre>\n<p>Then, in <code>myobject.h</code>, the wrapper class inherits from <code>node::ObjectWrap</code>:</p>\n<pre><code class=\"language-cpp\">// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include &#x3C;node.h>\n#include &#x3C;node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Local&#x3C;v8::Object> exports);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);\n  static void PlusOne(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);\n\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n</code></pre>\n<p>In <code>myobject.cc</code>, implement the various methods that are to be exposed.\nIn the following code, the method <code>plusOne()</code> is exposed by adding it to the\nconstructor's prototype:</p>\n<pre><code class=\"language-cpp\">// 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&#x3C;Object> exports) {\n  Isolate* isolate = Isolate::GetCurrent();\n  Local&#x3C;Context> context = isolate->GetCurrentContext();\n\n  Local&#x3C;ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);\n  addon_data_tpl->SetInternalFieldCount(1);  // 1 field for the MyObject::New()\n  Local&#x3C;Object> addon_data =\n      addon_data_tpl->NewInstance(context).ToLocalChecked();\n\n  // Prepare constructor template\n  Local&#x3C;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&#x3C;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&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n  Local&#x3C;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&#x3C;Value> argv[argc] = { args[0] };\n    Local&#x3C;Function> cons =\n        args.Data().As&#x3C;Object>()->GetInternalField(0)\n            .As&#x3C;Value>().As&#x3C;Function>();\n    Local&#x3C;Object> result =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(result);\n  }\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap&#x3C;MyObject>(args.This());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n</code></pre>\n<p>To build this example, the <code>myobject.cc</code> file must be added to the\n<code>binding.gyp</code>:</p>\n<pre><code class=\"language-json\">{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n</code></pre>\n<p>Test it with:</p>\n<pre><code class=\"language-js\">// 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</code></pre>\n<p>The 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.</p>\n<p>During 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.</p>",
              "displayName": "Wrapping C++ objects"
            },
            {
              "textRaw": "Factory of wrapped objects",
              "name": "factory_of_wrapped_objects",
              "type": "module",
              "desc": "<p>Alternatively, it is possible to use a factory pattern to avoid explicitly\ncreating object instances using the JavaScript <code>new</code> operator:</p>\n<pre><code class=\"language-js\">const obj = addon.createObject();\n// instead of:\n// const obj = new addon.Object();\n</code></pre>\n<p>First, the <code>createObject()</code> method is implemented in <code>addon.cc</code>:</p>\n<pre><code class=\"language-cpp\">// addon.cc\n#include &#x3C;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&#x3C;Value>&#x26; args) {\n  MyObject::NewInstance(args);\n}\n\nvoid InitAll(Local&#x3C;Object> exports, Local&#x3C;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</code></pre>\n<p>In <code>myobject.h</code>, the static method <code>NewInstance()</code> is added to handle\ninstantiating the object. This method takes the place of using <code>new</code> in\nJavaScript:</p>\n<pre><code class=\"language-cpp\">// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include &#x3C;node.h>\n#include &#x3C;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&#x3C;v8::Value>&#x26; args);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);\n  static void PlusOne(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);\n  static v8::Global&#x3C;v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n</code></pre>\n<p>The implementation in <code>myobject.cc</code> is similar to the previous example:</p>\n<pre><code class=\"language-cpp\">// myobject.cc\n#include &#x3C;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&#x3C;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&#x3C;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&#x3C;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&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n  Local&#x3C;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&#x3C;Value> argv[argc] = { args[0] };\n    Local&#x3C;Function> cons = Local&#x3C;Function>::New(isolate, constructor);\n    Local&#x3C;Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local&#x3C;Value> argv[argc] = { args[0] };\n  Local&#x3C;Function> cons = Local&#x3C;Function>::New(isolate, constructor);\n  Local&#x3C;Context> context = isolate->GetCurrentContext();\n  Local&#x3C;Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap&#x3C;MyObject>(args.This());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n</code></pre>\n<p>Once again, to build this example, the <code>myobject.cc</code> file must be added to the\n<code>binding.gyp</code>:</p>\n<pre><code class=\"language-json\">{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n</code></pre>\n<p>Test it with:</p>\n<pre><code class=\"language-js\">// 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</code></pre>",
              "displayName": "Factory of wrapped objects"
            },
            {
              "textRaw": "Passing wrapped objects around",
              "name": "passing_wrapped_objects_around",
              "type": "module",
              "desc": "<p>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<code>node::ObjectWrap::Unwrap</code>. The following examples shows a function <code>add()</code>\nthat can take two <code>MyObject</code> objects as input arguments:</p>\n<pre><code class=\"language-cpp\">// addon.cc\n#include &#x3C;node.h>\n#include &#x3C;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&#x3C;Value>&#x26; args) {\n  MyObject::NewInstance(args);\n}\n\nvoid Add(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n  Local&#x3C;Context> context = isolate->GetCurrentContext();\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap&#x3C;MyObject>(\n      args[0]->ToObject(context).ToLocalChecked());\n  MyObject* obj2 = node::ObjectWrap::Unwrap&#x3C;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&#x3C;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</code></pre>\n<p>In <code>myobject.h</code>, a new public method is added to allow access to private values\nafter unwrapping the object.</p>\n<pre><code class=\"language-cpp\">// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include &#x3C;node.h>\n#include &#x3C;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&#x3C;v8::Value>&#x26; 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&#x3C;v8::Value>&#x26; args);\n  static v8::Global&#x3C;v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n</code></pre>\n<p>The implementation of <code>myobject.cc</code> remains similar to the previous version:</p>\n<pre><code class=\"language-cpp\">// myobject.cc\n#include &#x3C;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&#x3C;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&#x3C;FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  Local&#x3C;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&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n  Local&#x3C;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&#x3C;Value> argv[argc] = { args[0] };\n    Local&#x3C;Function> cons = Local&#x3C;Function>::New(isolate, constructor);\n    Local&#x3C;Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local&#x3C;Value> argv[argc] = { args[0] };\n  Local&#x3C;Function> cons = Local&#x3C;Function>::New(isolate, constructor);\n  Local&#x3C;Context> context = isolate->GetCurrentContext();\n  Local&#x3C;Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\n}  // namespace demo\n</code></pre>\n<p>Test it with:</p>\n<pre><code class=\"language-js\">// 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</code></pre>",
              "displayName": "Passing wrapped objects around"
            }
          ],
          "displayName": "Addon examples"
        }
      ]
    }
  ]
}