1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width"> 6 <meta name="nodejs.org:node-version" content="v14.20.1"> 7 <title>C++ addons | Node.js v14.20.1 Documentation</title> 8 <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback"> 9 <link rel="stylesheet" href="assets/style.css"> 10 <link rel="stylesheet" href="assets/hljs.css"> 11 <link rel="canonical" href="https://nodejs.org/api/addons.html"> 12</head> 13<body class="alt apidoc" id="api-section-addons"> 14 <div id="content" class="clearfix"> 15 <div id="column2" class="interior"> 16 <div id="intro" class="interior"> 17 <a href="/" title="Go back to the home page"> 18 Node.js 19 </a> 20 </div> 21 <ul> 22<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 23<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 24</ul> 25<hr class="line"> 26<ul> 27<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 28<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 29<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 30<li><a href="addons.html" class="nav-addons active">C++ addons</a></li> 31<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 32<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 33<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 34<li><a href="cluster.html" class="nav-cluster">Cluster</a></li> 35<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 36<li><a href="console.html" class="nav-console">Console</a></li> 37<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 38<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 39<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 40<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 41<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 42<li><a href="dns.html" class="nav-dns">DNS</a></li> 43<li><a href="domain.html" class="nav-domain">Domain</a></li> 44<li><a href="errors.html" class="nav-errors">Errors</a></li> 45<li><a href="events.html" class="nav-events">Events</a></li> 46<li><a href="fs.html" class="nav-fs">File system</a></li> 47<li><a href="globals.html" class="nav-globals">Globals</a></li> 48<li><a href="http.html" class="nav-http">HTTP</a></li> 49<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 50<li><a href="https.html" class="nav-https">HTTPS</a></li> 51<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 52<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 53<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> 54<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> 55<li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li> 56<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 57<li><a href="net.html" class="nav-net">Net</a></li> 58<li><a href="os.html" class="nav-os">OS</a></li> 59<li><a href="path.html" class="nav-path">Path</a></li> 60<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 61<li><a href="policy.html" class="nav-policy">Policies</a></li> 62<li><a href="process.html" class="nav-process">Process</a></li> 63<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 64<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 65<li><a href="readline.html" class="nav-readline">Readline</a></li> 66<li><a href="repl.html" class="nav-repl">REPL</a></li> 67<li><a href="report.html" class="nav-report">Report</a></li> 68<li><a href="stream.html" class="nav-stream">Stream</a></li> 69<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 70<li><a href="timers.html" class="nav-timers">Timers</a></li> 71<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 72<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 73<li><a href="tty.html" class="nav-tty">TTY</a></li> 74<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> 75<li><a href="url.html" class="nav-url">URL</a></li> 76<li><a href="util.html" class="nav-util">Utilities</a></li> 77<li><a href="v8.html" class="nav-v8">V8</a></li> 78<li><a href="vm.html" class="nav-vm">VM</a></li> 79<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 80<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> 81<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 82</ul> 83<hr class="line"> 84<ul> 85<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 86</ul> 87 </div> 88 89 <div id="column1" data-id="addons" class="interior"> 90 <header> 91 <div class="header-container"> 92 <h1>Node.js v14.20.1 documentation</h1> 93 <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> 94 <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> 95 <path fill="none" d="M0 0h24v24H0z" /> 96 <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/> 97 <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/> 98 </svg> 99 <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> 100 <path d="M0 0h24v24H0z" fill="none" /> 101 <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/> 102 </svg> 103 </button> 104 </div> 105 <div id="gtoc"> 106 <ul> 107 <li> 108 <a href="index.html">Index</a> 109 </li> 110 <li> 111 <a href="all.html">View on single page</a> 112 </li> 113 <li> 114 <a href="addons.json">View as JSON</a> 115 </li> 116 117 <li class="version-picker"> 118 <a href="#">View another version <span>▼</span></a> 119 <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v18.x/api/addons.html">18.x</a></li> 120<li><a href="https://nodejs.org/docs/latest-v17.x/api/addons.html">17.x</a></li> 121<li><a href="https://nodejs.org/docs/latest-v16.x/api/addons.html">16.x <b>LTS</b></a></li> 122<li><a href="https://nodejs.org/docs/latest-v15.x/api/addons.html">15.x</a></li> 123<li><a href="https://nodejs.org/docs/latest-v14.x/api/addons.html">14.x <b>LTS</b></a></li> 124<li><a href="https://nodejs.org/docs/latest-v13.x/api/addons.html">13.x</a></li> 125<li><a href="https://nodejs.org/docs/latest-v12.x/api/addons.html">12.x <b>LTS</b></a></li> 126<li><a href="https://nodejs.org/docs/latest-v11.x/api/addons.html">11.x</a></li> 127<li><a href="https://nodejs.org/docs/latest-v10.x/api/addons.html">10.x</a></li> 128<li><a href="https://nodejs.org/docs/latest-v9.x/api/addons.html">9.x</a></li> 129<li><a href="https://nodejs.org/docs/latest-v8.x/api/addons.html">8.x</a></li> 130<li><a href="https://nodejs.org/docs/latest-v7.x/api/addons.html">7.x</a></li> 131<li><a href="https://nodejs.org/docs/latest-v6.x/api/addons.html">6.x</a></li> 132<li><a href="https://nodejs.org/docs/latest-v5.x/api/addons.html">5.x</a></li> 133<li><a href="https://nodejs.org/docs/latest-v4.x/api/addons.html">4.x</a></li> 134<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/addons.html">0.12.x</a></li> 135<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/addons.html">0.10.x</a></li></ol> 136 </li> 137 138 <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/addons.md">Edit on GitHub</a></li> 139 </ul> 140 </div> 141 <hr> 142 </header> 143 144 <details id="toc" open><summary>Table of contents</summary><ul> 145<li><a href="#addons_c_addons">C++ addons</a> 146<ul> 147<li><a href="#addons_hello_world">Hello world</a> 148<ul> 149<li><a href="#addons_context_aware_addons">Context-aware addons</a> 150<ul> 151<li><a href="#addons_worker_support">Worker support</a></li> 152</ul> 153</li> 154<li><a href="#addons_building">Building</a></li> 155<li><a href="#addons_linking_to_libraries_included_with_node_js">Linking to libraries included with Node.js</a></li> 156<li><a href="#addons_loading_addons_using_require">Loading addons using <code>require()</code></a></li> 157</ul> 158</li> 159<li><a href="#addons_native_abstractions_for_node_js">Native abstractions for Node.js</a></li> 160<li><span class="stability_2"><a href="#addons_node_api">Node-API</a></span></li> 161<li><a href="#addons_addon_examples">Addon examples</a> 162<ul> 163<li><a href="#addons_function_arguments">Function arguments</a></li> 164<li><a href="#addons_callbacks">Callbacks</a></li> 165<li><a href="#addons_object_factory">Object factory</a></li> 166<li><a href="#addons_function_factory">Function factory</a></li> 167<li><a href="#addons_wrapping_c_objects">Wrapping C++ objects</a></li> 168<li><a href="#addons_factory_of_wrapped_objects">Factory of wrapped objects</a></li> 169<li><a href="#addons_passing_wrapped_objects_around">Passing wrapped objects around</a></li> 170</ul> 171</li> 172</ul> 173</li> 174</ul></details> 175 176 <div id="apicontent"> 177 <h2>C++ addons<span><a class="mark" href="#addons_c_addons" id="addons_c_addons">#</a></span></h2> 178 179 180<p><em>Addons</em> are dynamically-linked shared objects written in C++. The 181<a href="modules.html#modules_require_id"><code>require()</code></a> function can load addons as ordinary Node.js modules. 182Addons provide an interface between JavaScript and C/C++ libraries.</p> 183<p>There are three options for implementing addons: Node-API, nan, or direct 184use of internal V8, libuv and Node.js libraries. Unless there is a need for 185direct access to functionality which is not exposed by Node-API, use Node-API. 186Refer to <a href="n-api.html">C/C++ addons with Node-API</a> for more information on 187Node-API.</p> 188<p>When not using Node-API, implementing addons is complicated, 189involving knowledge of several components and APIs:</p> 190<ul> 191<li> 192<p><a href="https://v8.dev/">V8</a>: the C++ library Node.js uses to provide the 193JavaScript implementation. V8 provides the mechanisms for creating objects, 194calling functions, etc. V8's API is documented mostly in the 195<code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node.js source 196tree), which is also available <a href="https://v8docs.nodesource.com/">online</a>.</p> 197</li> 198<li> 199<p><a href="https://github.com/libuv/libuv">libuv</a>: The C library that implements the Node.js event loop, its worker 200threads and all of the asynchronous behaviors of the platform. It also 201serves as a cross-platform abstraction library, giving easy, POSIX-like 202access across all major operating systems to many common system tasks, such 203as interacting with the filesystem, sockets, timers, and system events. libuv 204also provides a threading abstraction similar to POSIX threads for 205more sophisticated asynchronous addons that need to move beyond the 206standard event loop. Addon authors should 207avoid blocking the event loop with I/O or other time-intensive tasks by 208offloading work via libuv to non-blocking system operations, worker threads, 209or a custom use of libuv threads.</p> 210</li> 211<li> 212<p>Internal Node.js libraries. Node.js itself exports C++ APIs that addons can 213use, the most important of which is the <code>node::ObjectWrap</code> class.</p> 214</li> 215<li> 216<p>Node.js includes other statically linked libraries including OpenSSL. These 217other libraries are located in the <code>deps/</code> directory in the Node.js source 218tree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully 219re-exported by Node.js and may be used to various extents by addons. See 220<a href="#addons_linking_to_libraries_included_with_node_js">Linking to libraries included with Node.js</a> for additional information.</p> 221</li> 222</ul> 223<p>All of the following examples are available for <a href="https://github.com/nodejs/node-addon-examples">download</a> and may 224be used as the starting-point for an addon.</p> 225<section><h3>Hello world<span><a class="mark" href="#addons_hello_world" id="addons_hello_world">#</a></span></h3> 226<p>This "Hello world" example is a simple addon, written in C++, that is the 227equivalent of the following JavaScript code:</p> 228<pre><code class="language-js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">hello</span> = <span class="hljs-function">() =></span> <span class="hljs-string">'world'</span>;</code></pre> 229<p>First, create the file <code>hello.cc</code>:</p> 230<pre><code class="language-cpp"><span class="hljs-comment">// hello.cc</span> 231<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 232 233<span class="hljs-keyword">namespace</span> demo { 234 235<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 236<span class="hljs-keyword">using</span> v8::Isolate; 237<span class="hljs-keyword">using</span> v8::Local; 238<span class="hljs-keyword">using</span> v8::Object; 239<span class="hljs-keyword">using</span> v8::String; 240<span class="hljs-keyword">using</span> v8::Value; 241 242<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Method</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 243 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 244 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(String::<span class="hljs-built_in">NewFromUtf8</span>( 245 isolate, <span class="hljs-string">"world"</span>).<span class="hljs-built_in">ToLocalChecked</span>()); 246} 247 248<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Initialize</span><span class="hljs-params">(Local<Object> exports)</span> </span>{ 249 <span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"hello"</span>, Method); 250} 251 252<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Initialize) 253 254} <span class="hljs-comment">// namespace demo</span></code></pre> 255<p>All Node.js addons must export an initialization function following 256the pattern:</p> 257<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Initialize</span><span class="hljs-params">(Local<Object> exports)</span></span>; 258<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Initialize)</code></pre> 259<p>There is no semi-colon after <code>NODE_MODULE</code> as it's not a function (see 260<code>node.h</code>).</p> 261<p>The <code>module_name</code> must match the filename of the final binary (excluding 262the <code>.node</code> suffix).</p> 263<p>In the <code>hello.cc</code> example, then, the initialization function is <code>Initialize</code> 264and the addon module name is <code>addon</code>.</p> 265<p>When building addons with <code>node-gyp</code>, using the macro <code>NODE_GYP_MODULE_NAME</code> as 266the first parameter of <code>NODE_MODULE()</code> will ensure that the name of the final 267binary will be passed to <code>NODE_MODULE()</code>.</p> 268<h4>Context-aware addons<span><a class="mark" href="#addons_context_aware_addons" id="addons_context_aware_addons">#</a></span></h4> 269<p>There are environments in which Node.js addons may need to be loaded multiple 270times in multiple contexts. For example, the <a href="https://electronjs.org/">Electron</a> runtime runs multiple 271instances of Node.js in a single process. Each instance will have its own 272<code>require()</code> cache, and thus each instance will need a native addon to behave 273correctly when loaded via <code>require()</code>. This means that the addon 274must support multiple initializations.</p> 275<p>A context-aware addon can be constructed by using the macro 276<code>NODE_MODULE_INITIALIZER</code>, which expands to the name of a function which Node.js 277will expect to find when it loads an addon. An addon can thus be initialized as 278in the following example:</p> 279<pre><code class="language-cpp"><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> v8; 280 281<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function">NODE_MODULE_EXPORT <span class="hljs-type">void</span> 282<span class="hljs-title">NODE_MODULE_INITIALIZER</span><span class="hljs-params">(Local<Object> exports, 283 Local<Value> <span class="hljs-keyword">module</span>, 284 Local<Context> context)</span> </span>{ 285 <span class="hljs-comment">/* Perform addon initialization steps here. */</span> 286}</code></pre> 287<p>Another option is to use the macro <code>NODE_MODULE_INIT()</code>, which will also 288construct a context-aware addon. Unlike <code>NODE_MODULE()</code>, which is used to 289construct an addon around a given addon initializer function, 290<code>NODE_MODULE_INIT()</code> serves as the declaration of such an initializer to be 291followed by a function body.</p> 292<p>The following three variables may be used inside the function body following an 293invocation of <code>NODE_MODULE_INIT()</code>:</p> 294<ul> 295<li><code>Local<Object> exports</code>,</li> 296<li><code>Local<Value> module</code>, and</li> 297<li><code>Local<Context> context</code></li> 298</ul> 299<p>The choice to build a context-aware addon carries with it the responsibility of 300carefully managing global static data. Since the addon may be loaded multiple 301times, potentially even from different threads, any global static data stored 302in the addon must be properly protected, and must not contain any persistent 303references to JavaScript objects. The reason for this is that JavaScript 304objects are only valid in one context, and will likely cause a crash when 305accessed from the wrong context or from a different thread than the one on which 306they were created.</p> 307<p>The context-aware addon can be structured to avoid global static data by 308performing the following steps:</p> 309<ul> 310<li>Define a class which will hold per-addon-instance data and which has a static 311member of the form 312<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">DeleteInstance</span><span class="hljs-params">(<span class="hljs-type">void</span>* data)</span> </span>{ 313 <span class="hljs-comment">// Cast `data` to an instance of the class and delete it.</span> 314}</code></pre> 315</li> 316<li>Heap-allocate an instance of this class in the addon initializer. This can be 317accomplished using the <code>new</code> keyword.</li> 318<li>Call <code>node::AddEnvironmentCleanupHook()</code>, passing it the above-created 319instance and a pointer to <code>DeleteInstance()</code>. This will ensure the instance is 320deleted when the environment is torn down.</li> 321<li>Store the instance of the class in a <code>v8::External</code>, and</li> 322<li>Pass the <code>v8::External</code> to all methods exposed to JavaScript by passing it 323to <code>v8::FunctionTemplate::New()</code> or <code>v8::Function::New()</code> which creates the 324native-backed JavaScript functions. The third parameter of 325<code>v8::FunctionTemplate::New()</code> or <code>v8::Function::New()</code> accepts the 326<code>v8::External</code> and makes it available in the native callback using the 327<code>v8::FunctionCallbackInfo::Data()</code> method.</li> 328</ul> 329<p>This will ensure that the per-addon-instance data reaches each binding that can 330be called from JavaScript. The per-addon-instance data must also be passed into 331any asynchronous callbacks the addon may create.</p> 332<p>The following example illustrates the implementation of a context-aware addon:</p> 333<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 334 335<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> v8; 336 337<span class="hljs-keyword">class</span> <span class="hljs-title class_">AddonData</span> { 338 <span class="hljs-keyword">public</span>: 339 <span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">AddonData</span><span class="hljs-params">(Isolate* isolate)</span>: 340 call_count(<span class="hljs-number">0</span>) {</span> 341 <span class="hljs-comment">// Ensure this per-addon-instance data is deleted at environment cleanup.</span> 342 node::<span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, DeleteInstance, <span class="hljs-keyword">this</span>); 343 } 344 345 <span class="hljs-comment">// Per-addon data.</span> 346 <span class="hljs-type">int</span> call_count; 347 348 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">DeleteInstance</span><span class="hljs-params">(<span class="hljs-type">void</span>* data)</span> </span>{ 349 <span class="hljs-keyword">delete</span> <span class="hljs-built_in">static_cast</span><AddonData*>(data); 350 } 351}; 352 353<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Method</span><span class="hljs-params">(<span class="hljs-keyword">const</span> v8::FunctionCallbackInfo<v8::Value>& info)</span> </span>{ 354 <span class="hljs-comment">// Retrieve the per-addon-instance data.</span> 355 AddonData* data = 356 <span class="hljs-built_in">reinterpret_cast</span><AddonData*>(info.<span class="hljs-built_in">Data</span>().<span class="hljs-built_in">As</span><External>()-><span class="hljs-built_in">Value</span>()); 357 data->call_count++; 358 info.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>((<span class="hljs-type">double</span>)data->call_count); 359} 360 361<span class="hljs-comment">// Initialize this addon to be context-aware.</span> 362<span class="hljs-built_in">NODE_MODULE_INIT</span>(<span class="hljs-comment">/* exports, module, context */</span>) { 363 Isolate* isolate = context-><span class="hljs-built_in">GetIsolate</span>(); 364 365 <span class="hljs-comment">// Create a new instance of `AddonData` for this instance of the addon and</span> 366 <span class="hljs-comment">// tie its life cycle to that of the Node.js environment.</span> 367 AddonData* data = <span class="hljs-keyword">new</span> <span class="hljs-built_in">AddonData</span>(isolate); 368 369 <span class="hljs-comment">// Wrap the data in a `v8::External` so we can pass it to the method we</span> 370 <span class="hljs-comment">// expose.</span> 371 Local<External> external = External::<span class="hljs-built_in">New</span>(isolate, data); 372 373 <span class="hljs-comment">// Expose the method `Method` to JavaScript, and make sure it receives the</span> 374 <span class="hljs-comment">// per-addon-instance data we created above by passing `external` as the</span> 375 <span class="hljs-comment">// third parameter to the `FunctionTemplate` constructor.</span> 376 exports-><span class="hljs-built_in">Set</span>(context, 377 String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"method"</span>).<span class="hljs-built_in">ToLocalChecked</span>(), 378 FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, Method, external) 379 -><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>()).<span class="hljs-built_in">FromJust</span>(); 380}</code></pre> 381<h5>Worker support<span><a class="mark" href="#addons_worker_support" id="addons_worker_support">#</a></span></h5> 382<div class="api_metadata"> 383<details class="changelog"><summary>History</summary> 384<table> 385<tbody><tr><th>Version</th><th>Changes</th></tr> 386<tr><td>v14.8.0</td> 387<td><p>Cleanup hooks may now be asynchronous.</p></td></tr> 388</tbody></table> 389</details> 390</div> 391<p>In order to be loaded from multiple Node.js environments, 392such as a main thread and a Worker thread, an add-on needs to either:</p> 393<ul> 394<li>Be an Node-API addon, or</li> 395<li>Be declared as context-aware using <code>NODE_MODULE_INIT()</code> as described above</li> 396</ul> 397<p>In order to support <a href="worker_threads.html#worker_threads_class_worker"><code>Worker</code></a> threads, addons need to clean up any resources 398they may have allocated when such a thread exists. This can be achieved through 399the usage of the <code>AddEnvironmentCleanupHook()</code> function:</p> 400<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">AddEnvironmentCleanupHook</span><span class="hljs-params">(v8::Isolate* isolate, 401 <span class="hljs-type">void</span> (*fun)(<span class="hljs-type">void</span>* arg), 402 <span class="hljs-type">void</span>* arg)</span></span>;</code></pre> 403<p>This function adds a hook that will run before a given Node.js instance shuts 404down. If necessary, such hooks can be removed before they are run using 405<code>RemoveEnvironmentCleanupHook()</code>, which has the same signature. Callbacks are 406run in last-in first-out order.</p> 407<p>If necessary, there is an additional pair of <code>AddEnvironmentCleanupHook()</code> 408and <code>RemoveEnvironmentCleanupHook()</code> overloads, where the cleanup hook takes a 409callback function. This can be used for shutting down asynchronous resources, 410such as any libuv handles registered by the addon.</p> 411<p>The following <code>addon.cc</code> uses <code>AddEnvironmentCleanupHook</code>:</p> 412<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span> 413<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 414<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><assert.h></span></span> 415<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><stdlib.h></span></span> 416 417<span class="hljs-keyword">using</span> node::AddEnvironmentCleanupHook; 418<span class="hljs-keyword">using</span> v8::HandleScope; 419<span class="hljs-keyword">using</span> v8::Isolate; 420<span class="hljs-keyword">using</span> v8::Local; 421<span class="hljs-keyword">using</span> v8::Object; 422 423<span class="hljs-comment">// Note: In a real-world application, do not rely on static/global data.</span> 424<span class="hljs-keyword">static</span> <span class="hljs-type">char</span> cookie[] = <span class="hljs-string">"yum yum"</span>; 425<span class="hljs-keyword">static</span> <span class="hljs-type">int</span> cleanup_cb1_called = <span class="hljs-number">0</span>; 426<span class="hljs-keyword">static</span> <span class="hljs-type">int</span> cleanup_cb2_called = <span class="hljs-number">0</span>; 427 428<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">cleanup_cb1</span><span class="hljs-params">(<span class="hljs-type">void</span>* arg)</span> </span>{ 429 Isolate* isolate = <span class="hljs-built_in">static_cast</span><Isolate*>(arg); 430 <span class="hljs-function">HandleScope <span class="hljs-title">scope</span><span class="hljs-params">(isolate)</span></span>; 431 Local<Object> obj = Object::<span class="hljs-built_in">New</span>(isolate); 432 <span class="hljs-built_in">assert</span>(!obj.<span class="hljs-built_in">IsEmpty</span>()); <span class="hljs-comment">// assert VM is still alive</span> 433 <span class="hljs-built_in">assert</span>(obj-><span class="hljs-built_in">IsObject</span>()); 434 cleanup_cb1_called++; 435} 436 437<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">cleanup_cb2</span><span class="hljs-params">(<span class="hljs-type">void</span>* arg)</span> </span>{ 438 <span class="hljs-built_in">assert</span>(arg == <span class="hljs-built_in">static_cast</span><<span class="hljs-type">void</span>*>(cookie)); 439 cleanup_cb2_called++; 440} 441 442<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">sanity_check</span><span class="hljs-params">(<span class="hljs-type">void</span>*)</span> </span>{ 443 <span class="hljs-built_in">assert</span>(cleanup_cb1_called == <span class="hljs-number">1</span>); 444 <span class="hljs-built_in">assert</span>(cleanup_cb2_called == <span class="hljs-number">1</span>); 445} 446 447<span class="hljs-comment">// Initialize this addon to be context-aware.</span> 448<span class="hljs-built_in">NODE_MODULE_INIT</span>(<span class="hljs-comment">/* exports, module, context */</span>) { 449 Isolate* isolate = context-><span class="hljs-built_in">GetIsolate</span>(); 450 451 <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, sanity_check, <span class="hljs-literal">nullptr</span>); 452 <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, cleanup_cb2, cookie); 453 <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, cleanup_cb1, isolate); 454}</code></pre> 455<p>Test in JavaScript by running:</p> 456<pre><code class="language-js"><span class="hljs-comment">// test.js</span> 457<span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);</code></pre> 458<h4>Building<span><a class="mark" href="#addons_building" id="addons_building">#</a></span></h4> 459<p>Once the source code has been written, it must be compiled into the binary 460<code>addon.node</code> file. To do so, create a file called <code>binding.gyp</code> in the 461top-level of the project describing the build configuration of the module 462using a JSON-like format. This file is used by <a href="https://github.com/nodejs/node-gyp">node-gyp</a>, a tool written 463specifically to compile Node.js addons.</p> 464<pre><code class="language-json"><span class="hljs-punctuation">{</span> 465 <span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> 466 <span class="hljs-punctuation">{</span> 467 <span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span> 468 <span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> <span class="hljs-string">"hello.cc"</span> <span class="hljs-punctuation">]</span> 469 <span class="hljs-punctuation">}</span> 470 <span class="hljs-punctuation">]</span> 471<span class="hljs-punctuation">}</span></code></pre> 472<p>A version of the <code>node-gyp</code> utility is bundled and distributed with 473Node.js as part of <code>npm</code>. This version is not made directly available for 474developers to use and is intended only to support the ability to use the 475<code>npm install</code> command to compile and install addons. Developers who wish to 476use <code>node-gyp</code> directly can install it using the command 477<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 478more information, including platform-specific requirements.</p> 479<p>Once the <code>binding.gyp</code> file has been created, use <code>node-gyp configure</code> to 480generate the appropriate project build files for the current platform. This 481will generate either a <code>Makefile</code> (on Unix platforms) or a <code>vcxproj</code> file 482(on Windows) in the <code>build/</code> directory.</p> 483<p>Next, invoke the <code>node-gyp build</code> command to generate the compiled <code>addon.node</code> 484file. This will be put into the <code>build/Release/</code> directory.</p> 485<p>When using <code>npm install</code> to install a Node.js addon, npm uses its own bundled 486version of <code>node-gyp</code> to perform this same set of actions, generating a 487compiled version of the addon for the user's platform on demand.</p> 488<p>Once built, the binary addon can be used from within Node.js by pointing 489<a href="modules.html#modules_require_id"><code>require()</code></a> to the built <code>addon.node</code> module:</p> 490<pre><code class="language-js"><span class="hljs-comment">// hello.js</span> 491<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>); 492 493<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(addon.<span class="hljs-title function_">hello</span>()); 494<span class="hljs-comment">// Prints: 'world'</span></code></pre> 495<p>Because the exact path to the compiled addon binary can vary depending on how 496it is compiled (i.e. sometimes it may be in <code>./build/Debug/</code>), addons can use 497the <a href="https://github.com/TooTallNate/node-bindings">bindings</a> package to load the compiled module.</p> 498<p>While the <code>bindings</code> package implementation is more sophisticated in how it 499locates addon modules, it is essentially using a <code>try…catch</code> pattern similar to:</p> 500<pre><code class="language-js"><span class="hljs-keyword">try</span> { 501 <span class="hljs-keyword">return</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon.node'</span>); 502} <span class="hljs-keyword">catch</span> (err) { 503 <span class="hljs-keyword">return</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Debug/addon.node'</span>); 504}</code></pre> 505<h4>Linking to libraries included with Node.js<span><a class="mark" href="#addons_linking_to_libraries_included_with_node_js" id="addons_linking_to_libraries_included_with_node_js">#</a></span></h4> 506<p>Node.js uses statically linked libraries such as V8, libuv and OpenSSL. All 507addons are required to link to V8 and may link to any of the other dependencies 508as well. Typically, this is as simple as including the appropriate 509<code>#include <...></code> statements (e.g. <code>#include <v8.h></code>) and <code>node-gyp</code> will locate 510the appropriate headers automatically. However, there are a few caveats to be 511aware of:</p> 512<ul> 513<li> 514<p>When <code>node-gyp</code> runs, it will detect the specific release version of Node.js 515and download either the full source tarball or just the headers. If the full 516source is downloaded, addons will have complete access to the full set of 517Node.js dependencies. However, if only the Node.js headers are downloaded, 518then only the symbols exported by Node.js will be available.</p> 519</li> 520<li> 521<p><code>node-gyp</code> can be run using the <code>--nodedir</code> flag pointing at a local Node.js 522source image. Using this option, the addon will have access to the full set of 523dependencies.</p> 524</li> 525</ul> 526<h4>Loading addons using <code>require()</code><span><a class="mark" href="#addons_loading_addons_using_require" id="addons_loading_addons_using_require">#</a></span></h4> 527<p>The filename extension of the compiled addon binary is <code>.node</code> (as opposed 528to <code>.dll</code> or <code>.so</code>). The <a href="modules.html#modules_require_id"><code>require()</code></a> function is written to look for 529files with the <code>.node</code> file extension and initialize those as dynamically-linked 530libraries.</p> 531<p>When calling <a href="modules.html#modules_require_id"><code>require()</code></a>, the <code>.node</code> extension can usually be 532omitted and Node.js will still find and initialize the addon. One caveat, 533however, is that Node.js will first attempt to locate and load modules or 534JavaScript files that happen to share the same base name. For instance, if 535there is a file <code>addon.js</code> in the same directory as the binary <code>addon.node</code>, 536then <a href="modules.html#modules_require_id"><code>require('addon')</code></a> will give precedence to the <code>addon.js</code> file 537and load it instead.</p> 538</section><section><h3>Native abstractions for Node.js<span><a class="mark" href="#addons_native_abstractions_for_node_js" id="addons_native_abstractions_for_node_js">#</a></span></h3> 539<p>Each of the examples illustrated in this document directly use the 540Node.js and V8 APIs for implementing addons. The V8 API can, and has, changed 541dramatically from one V8 release to the next (and one major Node.js release to 542the next). With each change, addons may need to be updated and recompiled in 543order to continue functioning. The Node.js release schedule is designed to 544minimize the frequency and impact of such changes but there is little that 545Node.js can do to ensure stability of the V8 APIs.</p> 546<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 547addon developers are recommended to use to keep compatibility between past and 548future 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 549illustration of how it can be used.</p> 550</section><section><h3>Node-API<span><a class="mark" href="#addons_node_api" id="addons_node_api">#</a></span></h3> 551<p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> 552<p>Node-API is an API for building native addons. It is independent from 553the underlying JavaScript runtime (e.g. V8) and is maintained as part of 554Node.js itself. This API will be Application Binary Interface (ABI) stable 555across versions of Node.js. It is intended to insulate addons from 556changes in the underlying JavaScript engine and allow modules 557compiled for one version to run on later versions of Node.js without 558recompilation. Addons are built/packaged with the same approach/tools 559outlined in this document (node-gyp, etc.). The only difference is the 560set of APIs that are used by the native code. Instead of using the V8 561or <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a> APIs, the functions available 562in the Node-API are used.</p> 563<p>Creating and maintaining an addon that benefits from the ABI stability 564provided by Node-API carries with it certain 565<a href="n-api.html#n_api_implications_of_abi_stability">implementation considerations</a>.</p> 566<p>To use Node-API in the above "Hello world" example, replace the content of 567<code>hello.cc</code> with the following. All other instructions remain the same.</p> 568<pre><code class="language-cpp"><span class="hljs-comment">// hello.cc using Node-API</span> 569<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_api.h></span></span> 570 571<span class="hljs-keyword">namespace</span> demo { 572 573<span class="hljs-function">napi_value <span class="hljs-title">Method</span><span class="hljs-params">(napi_env env, napi_callback_info args)</span> </span>{ 574 napi_value greeting; 575 napi_status status; 576 577 status = <span class="hljs-built_in">napi_create_string_utf8</span>(env, <span class="hljs-string">"world"</span>, NAPI_AUTO_LENGTH, &greeting); 578 <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">nullptr</span>; 579 <span class="hljs-keyword">return</span> greeting; 580} 581 582<span class="hljs-function">napi_value <span class="hljs-title">init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> </span>{ 583 napi_status status; 584 napi_value fn; 585 586 status = <span class="hljs-built_in">napi_create_function</span>(env, <span class="hljs-literal">nullptr</span>, <span class="hljs-number">0</span>, Method, <span class="hljs-literal">nullptr</span>, &fn); 587 <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">nullptr</span>; 588 589 status = <span class="hljs-built_in">napi_set_named_property</span>(env, exports, <span class="hljs-string">"hello"</span>, fn); 590 <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">nullptr</span>; 591 <span class="hljs-keyword">return</span> exports; 592} 593 594<span class="hljs-built_in">NAPI_MODULE</span>(NODE_GYP_MODULE_NAME, init) 595 596} <span class="hljs-comment">// namespace demo</span></code></pre> 597<p>The functions available and how to use them are documented in 598<a href="n-api.html">C/C++ addons with Node-API</a>.</p> 599</section><section><h3>Addon examples<span><a class="mark" href="#addons_addon_examples" id="addons_addon_examples">#</a></span></h3> 600<p>Following are some example addons intended to help developers get started. The 601examples use the V8 APIs. Refer to the online <a href="https://v8docs.nodesource.com/">V8 reference</a> 602for help with the various V8 calls, and V8's <a href="https://github.com/v8/v8/wiki/Embedder's%20Guide">Embedder's Guide</a> for an 603explanation of several concepts used such as handles, scopes, function 604templates, etc.</p> 605<p>Each of these examples using the following <code>binding.gyp</code> file:</p> 606<pre><code class="language-json"><span class="hljs-punctuation">{</span> 607 <span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> 608 <span class="hljs-punctuation">{</span> 609 <span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span> 610 <span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> <span class="hljs-string">"addon.cc"</span> <span class="hljs-punctuation">]</span> 611 <span class="hljs-punctuation">}</span> 612 <span class="hljs-punctuation">]</span> 613<span class="hljs-punctuation">}</span></code></pre> 614<p>In cases where there is more than one <code>.cc</code> file, simply add the additional 615filename to the <code>sources</code> array:</p> 616<pre><code class="language-json"><span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-string">"addon.cc"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"myexample.cc"</span><span class="hljs-punctuation">]</span></code></pre> 617<p>Once the <code>binding.gyp</code> file is ready, the example addons can be configured and 618built using <code>node-gyp</code>:</p> 619<pre><code class="language-console"><span class="hljs-meta">$ </span><span class="language-bash">node-gyp configure build</span></code></pre> 620<h4>Function arguments<span><a class="mark" href="#addons_function_arguments" id="addons_function_arguments">#</a></span></h4> 621<p>Addons will typically expose objects and functions that can be accessed from 622JavaScript running within Node.js. When functions are invoked from JavaScript, 623the input arguments and return value must be mapped to and from the C/C++ 624code.</p> 625<p>The following example illustrates how to read function arguments passed from 626JavaScript and how to return a result:</p> 627<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span> 628<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 629 630<span class="hljs-keyword">namespace</span> demo { 631 632<span class="hljs-keyword">using</span> v8::Exception; 633<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 634<span class="hljs-keyword">using</span> v8::Isolate; 635<span class="hljs-keyword">using</span> v8::Local; 636<span class="hljs-keyword">using</span> v8::Number; 637<span class="hljs-keyword">using</span> v8::Object; 638<span class="hljs-keyword">using</span> v8::String; 639<span class="hljs-keyword">using</span> v8::Value; 640 641<span class="hljs-comment">// This is the implementation of the "add" method</span> 642<span class="hljs-comment">// Input arguments are passed using the</span> 643<span class="hljs-comment">// const FunctionCallbackInfo<Value>& args struct</span> 644<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Add</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 645 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 646 647 <span class="hljs-comment">// Check the number of arguments passed.</span> 648 <span class="hljs-keyword">if</span> (args.<span class="hljs-built_in">Length</span>() < <span class="hljs-number">2</span>) { 649 <span class="hljs-comment">// Throw an Error that is passed back to JavaScript</span> 650 isolate-><span class="hljs-built_in">ThrowException</span>(Exception::<span class="hljs-built_in">TypeError</span>( 651 String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, 652 <span class="hljs-string">"Wrong number of arguments"</span>).<span class="hljs-built_in">ToLocalChecked</span>())); 653 <span class="hljs-keyword">return</span>; 654 } 655 656 <span class="hljs-comment">// Check the argument types</span> 657 <span class="hljs-keyword">if</span> (!args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">IsNumber</span>() || !args[<span class="hljs-number">1</span>]-><span class="hljs-built_in">IsNumber</span>()) { 658 isolate-><span class="hljs-built_in">ThrowException</span>(Exception::<span class="hljs-built_in">TypeError</span>( 659 String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, 660 <span class="hljs-string">"Wrong arguments"</span>).<span class="hljs-built_in">ToLocalChecked</span>())); 661 <span class="hljs-keyword">return</span>; 662 } 663 664 <span class="hljs-comment">// Perform the operation</span> 665 <span class="hljs-type">double</span> value = 666 args[<span class="hljs-number">0</span>].<span class="hljs-built_in">As</span><Number>()-><span class="hljs-built_in">Value</span>() + args[<span class="hljs-number">1</span>].<span class="hljs-built_in">As</span><Number>()-><span class="hljs-built_in">Value</span>(); 667 Local<Number> num = Number::<span class="hljs-built_in">New</span>(isolate, value); 668 669 <span class="hljs-comment">// Set the return value (using the passed in</span> 670 <span class="hljs-comment">// FunctionCallbackInfo<Value>&)</span> 671 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(num); 672} 673 674<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local<Object> exports)</span> </span>{ 675 <span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"add"</span>, Add); 676} 677 678<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init) 679 680} <span class="hljs-comment">// namespace demo</span></code></pre> 681<p>Once compiled, the example addon can be required and used from within Node.js:</p> 682<pre><code class="language-js"><span class="hljs-comment">// test.js</span> 683<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>); 684 685<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This should be eight:'</span>, addon.<span class="hljs-title function_">add</span>(<span class="hljs-number">3</span>, <span class="hljs-number">5</span>));</code></pre> 686<h4>Callbacks<span><a class="mark" href="#addons_callbacks" id="addons_callbacks">#</a></span></h4> 687<p>It is common practice within addons to pass JavaScript functions to a C++ 688function and execute them from there. The following example illustrates how 689to invoke such callbacks:</p> 690<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span> 691<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 692 693<span class="hljs-keyword">namespace</span> demo { 694 695<span class="hljs-keyword">using</span> v8::Context; 696<span class="hljs-keyword">using</span> v8::Function; 697<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 698<span class="hljs-keyword">using</span> v8::Isolate; 699<span class="hljs-keyword">using</span> v8::Local; 700<span class="hljs-keyword">using</span> v8::Null; 701<span class="hljs-keyword">using</span> v8::Object; 702<span class="hljs-keyword">using</span> v8::String; 703<span class="hljs-keyword">using</span> v8::Value; 704 705<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">RunCallback</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 706 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 707 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 708 Local<Function> cb = Local<Function>::<span class="hljs-built_in">Cast</span>(args[<span class="hljs-number">0</span>]); 709 <span class="hljs-keyword">const</span> <span class="hljs-keyword">unsigned</span> argc = <span class="hljs-number">1</span>; 710 Local<Value> argv[argc] = { 711 String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, 712 <span class="hljs-string">"hello world"</span>).<span class="hljs-built_in">ToLocalChecked</span>() }; 713 cb-><span class="hljs-built_in">Call</span>(context, <span class="hljs-built_in">Null</span>(isolate), argc, argv).<span class="hljs-built_in">ToLocalChecked</span>(); 714} 715 716<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local<Object> exports, Local<Object> <span class="hljs-keyword">module</span>)</span> </span>{ 717 <span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, RunCallback); 718} 719 720<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init) 721 722} <span class="hljs-comment">// namespace demo</span></code></pre> 723<p>This example uses a two-argument form of <code>Init()</code> that receives the full 724<code>module</code> object as the second argument. This allows the addon to completely 725overwrite <code>exports</code> with a single function instead of adding the function as a 726property of <code>exports</code>.</p> 727<p>To test it, run the following JavaScript:</p> 728<pre><code class="language-js"><span class="hljs-comment">// test.js</span> 729<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>); 730 731<span class="hljs-title function_">addon</span>(<span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> { 732 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg); 733<span class="hljs-comment">// Prints: 'hello world'</span> 734});</code></pre> 735<p>In this example, the callback function is invoked synchronously.</p> 736<h4>Object factory<span><a class="mark" href="#addons_object_factory" id="addons_object_factory">#</a></span></h4> 737<p>Addons can create and return new objects from within a C++ function as 738illustrated in the following example. An object is created and returned with a 739property <code>msg</code> that echoes the string passed to <code>createObject()</code>:</p> 740<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span> 741<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 742 743<span class="hljs-keyword">namespace</span> demo { 744 745<span class="hljs-keyword">using</span> v8::Context; 746<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 747<span class="hljs-keyword">using</span> v8::Isolate; 748<span class="hljs-keyword">using</span> v8::Local; 749<span class="hljs-keyword">using</span> v8::Object; 750<span class="hljs-keyword">using</span> v8::String; 751<span class="hljs-keyword">using</span> v8::Value; 752 753<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateObject</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 754 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 755 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 756 757 Local<Object> obj = Object::<span class="hljs-built_in">New</span>(isolate); 758 obj-><span class="hljs-built_in">Set</span>(context, 759 String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, 760 <span class="hljs-string">"msg"</span>).<span class="hljs-built_in">ToLocalChecked</span>(), 761 args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">ToString</span>(context).<span class="hljs-built_in">ToLocalChecked</span>()) 762 .<span class="hljs-built_in">FromJust</span>(); 763 764 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(obj); 765} 766 767<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local<Object> exports, Local<Object> <span class="hljs-keyword">module</span>)</span> </span>{ 768 <span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, CreateObject); 769} 770 771<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init) 772 773} <span class="hljs-comment">// namespace demo</span></code></pre> 774<p>To test it in JavaScript:</p> 775<pre><code class="language-js"><span class="hljs-comment">// test.js</span> 776<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>); 777 778<span class="hljs-keyword">const</span> obj1 = <span class="hljs-title function_">addon</span>(<span class="hljs-string">'hello'</span>); 779<span class="hljs-keyword">const</span> obj2 = <span class="hljs-title function_">addon</span>(<span class="hljs-string">'world'</span>); 780<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj1.<span class="hljs-property">msg</span>, obj2.<span class="hljs-property">msg</span>); 781<span class="hljs-comment">// Prints: 'hello world'</span></code></pre> 782<h4>Function factory<span><a class="mark" href="#addons_function_factory" id="addons_function_factory">#</a></span></h4> 783<p>Another common scenario is creating JavaScript functions that wrap C++ 784functions and returning those back to JavaScript:</p> 785<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span> 786<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 787 788<span class="hljs-keyword">namespace</span> demo { 789 790<span class="hljs-keyword">using</span> v8::Context; 791<span class="hljs-keyword">using</span> v8::Function; 792<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 793<span class="hljs-keyword">using</span> v8::FunctionTemplate; 794<span class="hljs-keyword">using</span> v8::Isolate; 795<span class="hljs-keyword">using</span> v8::Local; 796<span class="hljs-keyword">using</span> v8::Object; 797<span class="hljs-keyword">using</span> v8::String; 798<span class="hljs-keyword">using</span> v8::Value; 799 800<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyFunction</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 801 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 802 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(String::<span class="hljs-built_in">NewFromUtf8</span>( 803 isolate, <span class="hljs-string">"hello world"</span>).<span class="hljs-built_in">ToLocalChecked</span>()); 804} 805 806<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateFunction</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 807 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 808 809 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 810 Local<FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, MyFunction); 811 Local<Function> fn = tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>(); 812 813 <span class="hljs-comment">// omit this to make it anonymous</span> 814 fn-><span class="hljs-built_in">SetName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>( 815 isolate, <span class="hljs-string">"theFunction"</span>).<span class="hljs-built_in">ToLocalChecked</span>()); 816 817 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(fn); 818} 819 820<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local<Object> exports, Local<Object> <span class="hljs-keyword">module</span>)</span> </span>{ 821 <span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, CreateFunction); 822} 823 824<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init) 825 826} <span class="hljs-comment">// namespace demo</span></code></pre> 827<p>To test:</p> 828<pre><code class="language-js"><span class="hljs-comment">// test.js</span> 829<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>); 830 831<span class="hljs-keyword">const</span> fn = <span class="hljs-title function_">addon</span>(); 832<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">fn</span>()); 833<span class="hljs-comment">// Prints: 'hello world'</span></code></pre> 834<h4>Wrapping C++ objects<span><a class="mark" href="#addons_wrapping_c_objects" id="addons_wrapping_c_objects">#</a></span></h4> 835<p>It is also possible to wrap C++ objects/classes in a way that allows new 836instances to be created using the JavaScript <code>new</code> operator:</p> 837<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span> 838<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 839<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span> 840 841<span class="hljs-keyword">namespace</span> demo { 842 843<span class="hljs-keyword">using</span> v8::Local; 844<span class="hljs-keyword">using</span> v8::Object; 845 846<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">InitAll</span><span class="hljs-params">(Local<Object> exports)</span> </span>{ 847 MyObject::<span class="hljs-built_in">Init</span>(exports); 848} 849 850<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, InitAll) 851 852} <span class="hljs-comment">// namespace demo</span></code></pre> 853<p>Then, in <code>myobject.h</code>, the wrapper class inherits from <code>node::ObjectWrap</code>:</p> 854<pre><code class="language-cpp"><span class="hljs-comment">// myobject.h</span> 855<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> MYOBJECT_H</span> 856<span class="hljs-meta">#<span class="hljs-keyword">define</span> MYOBJECT_H</span> 857 858<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 859<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_object_wrap.h></span></span> 860 861<span class="hljs-keyword">namespace</span> demo { 862 863<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyObject</span> : <span class="hljs-keyword">public</span> node::ObjectWrap { 864 <span class="hljs-keyword">public</span>: 865 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(v8::Local<v8::Object> exports)</span></span>; 866 867 <span class="hljs-keyword">private</span>: 868 <span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">MyObject</span><span class="hljs-params">(<span class="hljs-type">double</span> value = <span class="hljs-number">0</span>)</span></span>; 869 ~<span class="hljs-built_in">MyObject</span>(); 870 871 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">New</span><span class="hljs-params">(<span class="hljs-keyword">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>; 872 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">PlusOne</span><span class="hljs-params">(<span class="hljs-keyword">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>; 873 874 <span class="hljs-type">double</span> value_; 875}; 876 877} <span class="hljs-comment">// namespace demo</span> 878 879<span class="hljs-meta">#<span class="hljs-keyword">endif</span></span></code></pre> 880<p>In <code>myobject.cc</code>, implement the various methods that are to be exposed. 881Below, the method <code>plusOne()</code> is exposed by adding it to the constructor's 882prototype:</p> 883<pre><code class="language-cpp"><span class="hljs-comment">// myobject.cc</span> 884<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span> 885 886<span class="hljs-keyword">namespace</span> demo { 887 888<span class="hljs-keyword">using</span> v8::Context; 889<span class="hljs-keyword">using</span> v8::Function; 890<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 891<span class="hljs-keyword">using</span> v8::FunctionTemplate; 892<span class="hljs-keyword">using</span> v8::Isolate; 893<span class="hljs-keyword">using</span> v8::Local; 894<span class="hljs-keyword">using</span> v8::Number; 895<span class="hljs-keyword">using</span> v8::Object; 896<span class="hljs-keyword">using</span> v8::ObjectTemplate; 897<span class="hljs-keyword">using</span> v8::String; 898<span class="hljs-keyword">using</span> v8::Value; 899 900MyObject::<span class="hljs-built_in">MyObject</span>(<span class="hljs-type">double</span> value) : <span class="hljs-built_in">value_</span>(value) { 901} 902 903MyObject::~<span class="hljs-built_in">MyObject</span>() { 904} 905 906<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::Init</span><span class="hljs-params">(Local<Object> exports)</span> </span>{ 907 Isolate* isolate = exports-><span class="hljs-built_in">GetIsolate</span>(); 908 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 909 910 Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::<span class="hljs-built_in">New</span>(isolate); 911 addon_data_tpl-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>); <span class="hljs-comment">// 1 field for the MyObject::New()</span> 912 Local<Object> addon_data = 913 addon_data_tpl-><span class="hljs-built_in">NewInstance</span>(context).<span class="hljs-built_in">ToLocalChecked</span>(); 914 915 <span class="hljs-comment">// Prepare constructor template</span> 916 Local<FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, New, addon_data); 917 tpl-><span class="hljs-built_in">SetClassName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>()); 918 tpl-><span class="hljs-built_in">InstanceTemplate</span>()-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>); 919 920 <span class="hljs-comment">// Prototype</span> 921 <span class="hljs-built_in">NODE_SET_PROTOTYPE_METHOD</span>(tpl, <span class="hljs-string">"plusOne"</span>, PlusOne); 922 923 Local<Function> constructor = tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>(); 924 addon_data-><span class="hljs-built_in">SetInternalField</span>(<span class="hljs-number">0</span>, constructor); 925 exports-><span class="hljs-built_in">Set</span>(context, String::<span class="hljs-built_in">NewFromUtf8</span>( 926 isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>(), 927 constructor).<span class="hljs-built_in">FromJust</span>(); 928} 929 930<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::New</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 931 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 932 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 933 934 <span class="hljs-keyword">if</span> (args.<span class="hljs-built_in">IsConstructCall</span>()) { 935 <span class="hljs-comment">// Invoked as constructor: `new MyObject(...)`</span> 936 <span class="hljs-type">double</span> value = args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">IsUndefined</span>() ? 937 <span class="hljs-number">0</span> : args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">NumberValue</span>(context).<span class="hljs-built_in">FromMaybe</span>(<span class="hljs-number">0</span>); 938 MyObject* obj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">MyObject</span>(value); 939 obj-><span class="hljs-built_in">Wrap</span>(args.<span class="hljs-built_in">This</span>()); 940 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(args.<span class="hljs-built_in">This</span>()); 941 } <span class="hljs-keyword">else</span> { 942 <span class="hljs-comment">// Invoked as plain function `MyObject(...)`, turn into construct call.</span> 943 <span class="hljs-keyword">const</span> <span class="hljs-type">int</span> argc = <span class="hljs-number">1</span>; 944 Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] }; 945 Local<Function> cons = 946 args.<span class="hljs-built_in">Data</span>().<span class="hljs-built_in">As</span><Object>()-><span class="hljs-built_in">GetInternalField</span>(<span class="hljs-number">0</span>).<span class="hljs-built_in">As</span><Function>(); 947 Local<Object> result = 948 cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>(); 949 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(result); 950 } 951} 952 953<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::PlusOne</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 954 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 955 956 MyObject* obj = ObjectWrap::<span class="hljs-built_in">Unwrap</span><MyObject>(args.<span class="hljs-built_in">Holder</span>()); 957 obj->value_ += <span class="hljs-number">1</span>; 958 959 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(Number::<span class="hljs-built_in">New</span>(isolate, obj->value_)); 960} 961 962} <span class="hljs-comment">// namespace demo</span></code></pre> 963<p>To build this example, the <code>myobject.cc</code> file must be added to the 964<code>binding.gyp</code>:</p> 965<pre><code class="language-json"><span class="hljs-punctuation">{</span> 966 <span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> 967 <span class="hljs-punctuation">{</span> 968 <span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span> 969 <span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> 970 <span class="hljs-string">"addon.cc"</span><span class="hljs-punctuation">,</span> 971 <span class="hljs-string">"myobject.cc"</span> 972 <span class="hljs-punctuation">]</span> 973 <span class="hljs-punctuation">}</span> 974 <span class="hljs-punctuation">]</span> 975<span class="hljs-punctuation">}</span></code></pre> 976<p>Test it with:</p> 977<pre><code class="language-js"><span class="hljs-comment">// test.js</span> 978<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>); 979 980<span class="hljs-keyword">const</span> obj = <span class="hljs-keyword">new</span> addon.<span class="hljs-title class_">MyObject</span>(<span class="hljs-number">10</span>); 981<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>()); 982<span class="hljs-comment">// Prints: 11</span> 983<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>()); 984<span class="hljs-comment">// Prints: 12</span> 985<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>()); 986<span class="hljs-comment">// Prints: 13</span></code></pre> 987<p>The destructor for a wrapper object will run when the object is 988garbage-collected. For destructor testing, there are command-line flags that 989can be used to make it possible to force garbage collection. These flags are 990provided by the underlying V8 JavaScript engine. They are subject to change 991or removal at any time. They are not documented by Node.js or V8, and they 992should never be used outside of testing.</p> 993<h4>Factory of wrapped objects<span><a class="mark" href="#addons_factory_of_wrapped_objects" id="addons_factory_of_wrapped_objects">#</a></span></h4> 994<p>Alternatively, it is possible to use a factory pattern to avoid explicitly 995creating object instances using the JavaScript <code>new</code> operator:</p> 996<pre><code class="language-js"><span class="hljs-keyword">const</span> obj = addon.<span class="hljs-title function_">createObject</span>(); 997<span class="hljs-comment">// instead of:</span> 998<span class="hljs-comment">// const obj = new addon.Object();</span></code></pre> 999<p>First, the <code>createObject()</code> method is implemented in <code>addon.cc</code>:</p> 1000<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span> 1001<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 1002<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span> 1003 1004<span class="hljs-keyword">namespace</span> demo { 1005 1006<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 1007<span class="hljs-keyword">using</span> v8::Isolate; 1008<span class="hljs-keyword">using</span> v8::Local; 1009<span class="hljs-keyword">using</span> v8::Object; 1010<span class="hljs-keyword">using</span> v8::String; 1011<span class="hljs-keyword">using</span> v8::Value; 1012 1013<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateObject</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 1014 MyObject::<span class="hljs-built_in">NewInstance</span>(args); 1015} 1016 1017<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">InitAll</span><span class="hljs-params">(Local<Object> exports, Local<Object> <span class="hljs-keyword">module</span>)</span> </span>{ 1018 MyObject::<span class="hljs-built_in">Init</span>(exports-><span class="hljs-built_in">GetIsolate</span>()); 1019 1020 <span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, CreateObject); 1021} 1022 1023<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, InitAll) 1024 1025} <span class="hljs-comment">// namespace demo</span></code></pre> 1026<p>In <code>myobject.h</code>, the static method <code>NewInstance()</code> is added to handle 1027instantiating the object. This method takes the place of using <code>new</code> in 1028JavaScript:</p> 1029<pre><code class="language-cpp"><span class="hljs-comment">// myobject.h</span> 1030<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> MYOBJECT_H</span> 1031<span class="hljs-meta">#<span class="hljs-keyword">define</span> MYOBJECT_H</span> 1032 1033<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 1034<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_object_wrap.h></span></span> 1035 1036<span class="hljs-keyword">namespace</span> demo { 1037 1038<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyObject</span> : <span class="hljs-keyword">public</span> node::ObjectWrap { 1039 <span class="hljs-keyword">public</span>: 1040 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(v8::Isolate* isolate)</span></span>; 1041 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">NewInstance</span><span class="hljs-params">(<span class="hljs-keyword">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>; 1042 1043 <span class="hljs-keyword">private</span>: 1044 <span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">MyObject</span><span class="hljs-params">(<span class="hljs-type">double</span> value = <span class="hljs-number">0</span>)</span></span>; 1045 ~<span class="hljs-built_in">MyObject</span>(); 1046 1047 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">New</span><span class="hljs-params">(<span class="hljs-keyword">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>; 1048 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">PlusOne</span><span class="hljs-params">(<span class="hljs-keyword">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>; 1049 <span class="hljs-keyword">static</span> v8::Global<v8::Function> constructor; 1050 <span class="hljs-type">double</span> value_; 1051}; 1052 1053} <span class="hljs-comment">// namespace demo</span> 1054 1055<span class="hljs-meta">#<span class="hljs-keyword">endif</span></span></code></pre> 1056<p>The implementation in <code>myobject.cc</code> is similar to the previous example:</p> 1057<pre><code class="language-cpp"><span class="hljs-comment">// myobject.cc</span> 1058<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 1059<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span> 1060 1061<span class="hljs-keyword">namespace</span> demo { 1062 1063<span class="hljs-keyword">using</span> node::AddEnvironmentCleanupHook; 1064<span class="hljs-keyword">using</span> v8::Context; 1065<span class="hljs-keyword">using</span> v8::Function; 1066<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 1067<span class="hljs-keyword">using</span> v8::FunctionTemplate; 1068<span class="hljs-keyword">using</span> v8::Global; 1069<span class="hljs-keyword">using</span> v8::Isolate; 1070<span class="hljs-keyword">using</span> v8::Local; 1071<span class="hljs-keyword">using</span> v8::Number; 1072<span class="hljs-keyword">using</span> v8::Object; 1073<span class="hljs-keyword">using</span> v8::String; 1074<span class="hljs-keyword">using</span> v8::Value; 1075 1076<span class="hljs-comment">// Warning! This is not thread-safe, this addon cannot be used for worker</span> 1077<span class="hljs-comment">// threads.</span> 1078Global<Function> MyObject::constructor; 1079 1080MyObject::<span class="hljs-built_in">MyObject</span>(<span class="hljs-type">double</span> value) : <span class="hljs-built_in">value_</span>(value) { 1081} 1082 1083MyObject::~<span class="hljs-built_in">MyObject</span>() { 1084} 1085 1086<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::Init</span><span class="hljs-params">(Isolate* isolate)</span> </span>{ 1087 <span class="hljs-comment">// Prepare constructor template</span> 1088 Local<FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, New); 1089 tpl-><span class="hljs-built_in">SetClassName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>()); 1090 tpl-><span class="hljs-built_in">InstanceTemplate</span>()-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>); 1091 1092 <span class="hljs-comment">// Prototype</span> 1093 <span class="hljs-built_in">NODE_SET_PROTOTYPE_METHOD</span>(tpl, <span class="hljs-string">"plusOne"</span>, PlusOne); 1094 1095 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 1096 constructor.<span class="hljs-built_in">Reset</span>(isolate, tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>()); 1097 1098 <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, [](<span class="hljs-type">void</span>*) { 1099 constructor.<span class="hljs-built_in">Reset</span>(); 1100 }, <span class="hljs-literal">nullptr</span>); 1101} 1102 1103<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::New</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 1104 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 1105 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 1106 1107 <span class="hljs-keyword">if</span> (args.<span class="hljs-built_in">IsConstructCall</span>()) { 1108 <span class="hljs-comment">// Invoked as constructor: `new MyObject(...)`</span> 1109 <span class="hljs-type">double</span> value = args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">IsUndefined</span>() ? 1110 <span class="hljs-number">0</span> : args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">NumberValue</span>(context).<span class="hljs-built_in">FromMaybe</span>(<span class="hljs-number">0</span>); 1111 MyObject* obj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">MyObject</span>(value); 1112 obj-><span class="hljs-built_in">Wrap</span>(args.<span class="hljs-built_in">This</span>()); 1113 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(args.<span class="hljs-built_in">This</span>()); 1114 } <span class="hljs-keyword">else</span> { 1115 <span class="hljs-comment">// Invoked as plain function `MyObject(...)`, turn into construct call.</span> 1116 <span class="hljs-keyword">const</span> <span class="hljs-type">int</span> argc = <span class="hljs-number">1</span>; 1117 Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] }; 1118 Local<Function> cons = Local<Function>::<span class="hljs-built_in">New</span>(isolate, constructor); 1119 Local<Object> instance = 1120 cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>(); 1121 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance); 1122 } 1123} 1124 1125<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::NewInstance</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 1126 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 1127 1128 <span class="hljs-keyword">const</span> <span class="hljs-keyword">unsigned</span> argc = <span class="hljs-number">1</span>; 1129 Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] }; 1130 Local<Function> cons = Local<Function>::<span class="hljs-built_in">New</span>(isolate, constructor); 1131 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 1132 Local<Object> instance = 1133 cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>(); 1134 1135 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance); 1136} 1137 1138<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::PlusOne</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 1139 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 1140 1141 MyObject* obj = ObjectWrap::<span class="hljs-built_in">Unwrap</span><MyObject>(args.<span class="hljs-built_in">Holder</span>()); 1142 obj->value_ += <span class="hljs-number">1</span>; 1143 1144 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(Number::<span class="hljs-built_in">New</span>(isolate, obj->value_)); 1145} 1146 1147} <span class="hljs-comment">// namespace demo</span></code></pre> 1148<p>Once again, to build this example, the <code>myobject.cc</code> file must be added to the 1149<code>binding.gyp</code>:</p> 1150<pre><code class="language-json"><span class="hljs-punctuation">{</span> 1151 <span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> 1152 <span class="hljs-punctuation">{</span> 1153 <span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span> 1154 <span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> 1155 <span class="hljs-string">"addon.cc"</span><span class="hljs-punctuation">,</span> 1156 <span class="hljs-string">"myobject.cc"</span> 1157 <span class="hljs-punctuation">]</span> 1158 <span class="hljs-punctuation">}</span> 1159 <span class="hljs-punctuation">]</span> 1160<span class="hljs-punctuation">}</span></code></pre> 1161<p>Test it with:</p> 1162<pre><code class="language-js"><span class="hljs-comment">// test.js</span> 1163<span class="hljs-keyword">const</span> createObject = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>); 1164 1165<span class="hljs-keyword">const</span> obj = <span class="hljs-title function_">createObject</span>(<span class="hljs-number">10</span>); 1166<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>()); 1167<span class="hljs-comment">// Prints: 11</span> 1168<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>()); 1169<span class="hljs-comment">// Prints: 12</span> 1170<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>()); 1171<span class="hljs-comment">// Prints: 13</span> 1172 1173<span class="hljs-keyword">const</span> obj2 = <span class="hljs-title function_">createObject</span>(<span class="hljs-number">20</span>); 1174<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-title function_">plusOne</span>()); 1175<span class="hljs-comment">// Prints: 21</span> 1176<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-title function_">plusOne</span>()); 1177<span class="hljs-comment">// Prints: 22</span> 1178<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-title function_">plusOne</span>()); 1179<span class="hljs-comment">// Prints: 23</span></code></pre> 1180<h4>Passing wrapped objects around<span><a class="mark" href="#addons_passing_wrapped_objects_around" id="addons_passing_wrapped_objects_around">#</a></span></h4> 1181<p>In addition to wrapping and returning C++ objects, it is possible to pass 1182wrapped objects around by unwrapping them with the Node.js helper function 1183<code>node::ObjectWrap::Unwrap</code>. The following examples shows a function <code>add()</code> 1184that can take two <code>MyObject</code> objects as input arguments:</p> 1185<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span> 1186<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 1187<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_object_wrap.h></span></span> 1188<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span> 1189 1190<span class="hljs-keyword">namespace</span> demo { 1191 1192<span class="hljs-keyword">using</span> v8::Context; 1193<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 1194<span class="hljs-keyword">using</span> v8::Isolate; 1195<span class="hljs-keyword">using</span> v8::Local; 1196<span class="hljs-keyword">using</span> v8::Number; 1197<span class="hljs-keyword">using</span> v8::Object; 1198<span class="hljs-keyword">using</span> v8::String; 1199<span class="hljs-keyword">using</span> v8::Value; 1200 1201<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateObject</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 1202 MyObject::<span class="hljs-built_in">NewInstance</span>(args); 1203} 1204 1205<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Add</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 1206 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 1207 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 1208 1209 MyObject* obj1 = node::ObjectWrap::<span class="hljs-built_in">Unwrap</span><MyObject>( 1210 args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">ToObject</span>(context).<span class="hljs-built_in">ToLocalChecked</span>()); 1211 MyObject* obj2 = node::ObjectWrap::<span class="hljs-built_in">Unwrap</span><MyObject>( 1212 args[<span class="hljs-number">1</span>]-><span class="hljs-built_in">ToObject</span>(context).<span class="hljs-built_in">ToLocalChecked</span>()); 1213 1214 <span class="hljs-type">double</span> sum = obj1-><span class="hljs-built_in">value</span>() + obj2-><span class="hljs-built_in">value</span>(); 1215 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(Number::<span class="hljs-built_in">New</span>(isolate, sum)); 1216} 1217 1218<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">InitAll</span><span class="hljs-params">(Local<Object> exports)</span> </span>{ 1219 MyObject::<span class="hljs-built_in">Init</span>(exports-><span class="hljs-built_in">GetIsolate</span>()); 1220 1221 <span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"createObject"</span>, CreateObject); 1222 <span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"add"</span>, Add); 1223} 1224 1225<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, InitAll) 1226 1227} <span class="hljs-comment">// namespace demo</span></code></pre> 1228<p>In <code>myobject.h</code>, a new public method is added to allow access to private values 1229after unwrapping the object.</p> 1230<pre><code class="language-cpp"><span class="hljs-comment">// myobject.h</span> 1231<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> MYOBJECT_H</span> 1232<span class="hljs-meta">#<span class="hljs-keyword">define</span> MYOBJECT_H</span> 1233 1234<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 1235<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_object_wrap.h></span></span> 1236 1237<span class="hljs-keyword">namespace</span> demo { 1238 1239<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyObject</span> : <span class="hljs-keyword">public</span> node::ObjectWrap { 1240 <span class="hljs-keyword">public</span>: 1241 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(v8::Isolate* isolate)</span></span>; 1242 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">NewInstance</span><span class="hljs-params">(<span class="hljs-keyword">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>; 1243 <span class="hljs-function"><span class="hljs-keyword">inline</span> <span class="hljs-type">double</span> <span class="hljs-title">value</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span> </span>{ <span class="hljs-keyword">return</span> value_; } 1244 1245 <span class="hljs-keyword">private</span>: 1246 <span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">MyObject</span><span class="hljs-params">(<span class="hljs-type">double</span> value = <span class="hljs-number">0</span>)</span></span>; 1247 ~<span class="hljs-built_in">MyObject</span>(); 1248 1249 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-type">void</span> <span class="hljs-title">New</span><span class="hljs-params">(<span class="hljs-keyword">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>; 1250 <span class="hljs-keyword">static</span> v8::Global<v8::Function> constructor; 1251 <span class="hljs-type">double</span> value_; 1252}; 1253 1254} <span class="hljs-comment">// namespace demo</span> 1255 1256<span class="hljs-meta">#<span class="hljs-keyword">endif</span></span></code></pre> 1257<p>The implementation of <code>myobject.cc</code> is similar to before:</p> 1258<pre><code class="language-cpp"><span class="hljs-comment">// myobject.cc</span> 1259<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span> 1260<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span> 1261 1262<span class="hljs-keyword">namespace</span> demo { 1263 1264<span class="hljs-keyword">using</span> node::AddEnvironmentCleanupHook; 1265<span class="hljs-keyword">using</span> v8::Context; 1266<span class="hljs-keyword">using</span> v8::Function; 1267<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo; 1268<span class="hljs-keyword">using</span> v8::FunctionTemplate; 1269<span class="hljs-keyword">using</span> v8::Global; 1270<span class="hljs-keyword">using</span> v8::Isolate; 1271<span class="hljs-keyword">using</span> v8::Local; 1272<span class="hljs-keyword">using</span> v8::Object; 1273<span class="hljs-keyword">using</span> v8::String; 1274<span class="hljs-keyword">using</span> v8::Value; 1275 1276<span class="hljs-comment">// Warning! This is not thread-safe, this addon cannot be used for worker</span> 1277<span class="hljs-comment">// threads.</span> 1278Global<Function> MyObject::constructor; 1279 1280MyObject::<span class="hljs-built_in">MyObject</span>(<span class="hljs-type">double</span> value) : <span class="hljs-built_in">value_</span>(value) { 1281} 1282 1283MyObject::~<span class="hljs-built_in">MyObject</span>() { 1284} 1285 1286<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::Init</span><span class="hljs-params">(Isolate* isolate)</span> </span>{ 1287 <span class="hljs-comment">// Prepare constructor template</span> 1288 Local<FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, New); 1289 tpl-><span class="hljs-built_in">SetClassName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>()); 1290 tpl-><span class="hljs-built_in">InstanceTemplate</span>()-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>); 1291 1292 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 1293 constructor.<span class="hljs-built_in">Reset</span>(isolate, tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>()); 1294 1295 <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, [](<span class="hljs-type">void</span>*) { 1296 constructor.<span class="hljs-built_in">Reset</span>(); 1297 }, <span class="hljs-literal">nullptr</span>); 1298} 1299 1300<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::New</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 1301 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 1302 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 1303 1304 <span class="hljs-keyword">if</span> (args.<span class="hljs-built_in">IsConstructCall</span>()) { 1305 <span class="hljs-comment">// Invoked as constructor: `new MyObject(...)`</span> 1306 <span class="hljs-type">double</span> value = args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">IsUndefined</span>() ? 1307 <span class="hljs-number">0</span> : args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">NumberValue</span>(context).<span class="hljs-built_in">FromMaybe</span>(<span class="hljs-number">0</span>); 1308 MyObject* obj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">MyObject</span>(value); 1309 obj-><span class="hljs-built_in">Wrap</span>(args.<span class="hljs-built_in">This</span>()); 1310 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(args.<span class="hljs-built_in">This</span>()); 1311 } <span class="hljs-keyword">else</span> { 1312 <span class="hljs-comment">// Invoked as plain function `MyObject(...)`, turn into construct call.</span> 1313 <span class="hljs-keyword">const</span> <span class="hljs-type">int</span> argc = <span class="hljs-number">1</span>; 1314 Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] }; 1315 Local<Function> cons = Local<Function>::<span class="hljs-built_in">New</span>(isolate, constructor); 1316 Local<Object> instance = 1317 cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>(); 1318 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance); 1319 } 1320} 1321 1322<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::NewInstance</span><span class="hljs-params">(<span class="hljs-keyword">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{ 1323 Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>(); 1324 1325 <span class="hljs-keyword">const</span> <span class="hljs-keyword">unsigned</span> argc = <span class="hljs-number">1</span>; 1326 Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] }; 1327 Local<Function> cons = Local<Function>::<span class="hljs-built_in">New</span>(isolate, constructor); 1328 Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>(); 1329 Local<Object> instance = 1330 cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>(); 1331 1332 args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance); 1333} 1334 1335} <span class="hljs-comment">// namespace demo</span></code></pre> 1336<p>Test it with:</p> 1337<pre><code class="language-js"><span class="hljs-comment">// test.js</span> 1338<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>); 1339 1340<span class="hljs-keyword">const</span> obj1 = addon.<span class="hljs-title function_">createObject</span>(<span class="hljs-number">10</span>); 1341<span class="hljs-keyword">const</span> obj2 = addon.<span class="hljs-title function_">createObject</span>(<span class="hljs-number">20</span>); 1342<span class="hljs-keyword">const</span> result = addon.<span class="hljs-title function_">add</span>(obj1, obj2); 1343 1344<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); 1345<span class="hljs-comment">// Prints: 30</span></code></pre></section> 1346 <!-- API END --> 1347 </div> 1348 </div> 1349 </div> 1350 <script> 1351 'use strict'; 1352 { 1353 const kCustomPreference = 'customDarkTheme'; 1354 const userSettings = sessionStorage.getItem(kCustomPreference); 1355 const themeToggleButton = document.getElementById('theme-toggle-btn'); 1356 if (userSettings === null && window.matchMedia) { 1357 const mq = window.matchMedia('(prefers-color-scheme: dark)'); 1358 if ('onchange' in mq) { 1359 function mqChangeListener(e) { 1360 document.body.classList.toggle('dark-mode', e.matches); 1361 } 1362 mq.addEventListener('change', mqChangeListener); 1363 if (themeToggleButton) { 1364 themeToggleButton.addEventListener('click', function() { 1365 mq.removeEventListener('change', mqChangeListener); 1366 }, { once: true }); 1367 } 1368 } 1369 if (mq.matches) { 1370 document.body.classList.add('dark-mode'); 1371 } 1372 } else if (userSettings === 'true') { 1373 document.body.classList.add('dark-mode'); 1374 } 1375 if (themeToggleButton) { 1376 themeToggleButton.hidden = false; 1377 themeToggleButton.addEventListener('click', function() { 1378 sessionStorage.setItem( 1379 kCustomPreference, 1380 document.body.classList.toggle('dark-mode') 1381 ); 1382 }); 1383 } 1384 } 1385 </script> 1386</body> 1387</html> 1388