• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.19.1">
7  <title>Node-API | Node.js v14.19.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/n-api.html">
12</head>
13<body class="alt apidoc" id="api-section-n-api">
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">C++ addons</a></li>
31<li><a href="n-api.html" class="nav-n-api active">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="n-api" class="interior">
90      <header>
91        <div class="header-container">
92          <h1>Node.js v14.19.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="n-api.json">View as JSON</a>
115            </li>
116
117    <li class="version-picker">
118      <a href="#">View another version <span>&#x25bc;</span></a>
119      <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v17.x/api/n-api.html">17.x</a></li>
120<li><a href="https://nodejs.org/docs/latest-v16.x/api/n-api.html">16.x <b>LTS</b></a></li>
121<li><a href="https://nodejs.org/docs/latest-v15.x/api/n-api.html">15.x</a></li>
122<li><a href="https://nodejs.org/docs/latest-v14.x/api/n-api.html">14.x <b>LTS</b></a></li>
123<li><a href="https://nodejs.org/docs/latest-v13.x/api/n-api.html">13.x</a></li>
124<li><a href="https://nodejs.org/docs/latest-v12.x/api/n-api.html">12.x <b>LTS</b></a></li>
125<li><a href="https://nodejs.org/docs/latest-v11.x/api/n-api.html">11.x</a></li>
126<li><a href="https://nodejs.org/docs/latest-v10.x/api/n-api.html">10.x</a></li>
127<li><a href="https://nodejs.org/docs/latest-v9.x/api/n-api.html">9.x</a></li>
128<li><a href="https://nodejs.org/docs/latest-v8.x/api/n-api.html">8.x</a></li></ol>
129    </li>
130
131            <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/n-api.md">Edit on GitHub</a></li>
132          </ul>
133        </div>
134        <hr>
135      </header>
136
137      <details id="toc" open><summary>Table of contents</summary><ul>
138<li><span class="stability_2"><a href="#n_api_node_api">Node-API</a></span>
139<ul>
140<li><a href="#n_api_implications_of_abi_stability">Implications of ABI stability</a></li>
141<li><a href="#n_api_building">Building</a>
142<ul>
143<li><a href="#n_api_build_tools">Build tools</a>
144<ul>
145<li><a href="#n_api_node_gyp">node-gyp</a></li>
146<li><a href="#n_api_cmake_js">CMake.js</a></li>
147</ul>
148</li>
149<li><a href="#n_api_uploading_precompiled_binaries">Uploading precompiled binaries</a>
150<ul>
151<li><a href="#n_api_node_pre_gyp">node-pre-gyp</a></li>
152<li><a href="#n_api_prebuild">prebuild</a></li>
153<li><a href="#n_api_prebuildify">prebuildify</a></li>
154</ul>
155</li>
156</ul>
157</li>
158<li><a href="#n_api_usage">Usage</a></li>
159<li><a href="#n_api_node_api_version_matrix">Node-API version matrix</a></li>
160<li><a href="#n_api_environment_life_cycle_apis">Environment life cycle APIs</a>
161<ul>
162<li><a href="#n_api_napi_set_instance_data">napi_set_instance_data</a></li>
163<li><a href="#n_api_napi_get_instance_data">napi_get_instance_data</a></li>
164</ul>
165</li>
166<li><a href="#n_api_basic_node_api_data_types">Basic Node-API data types</a>
167<ul>
168<li><a href="#n_api_napi_status">napi_status</a></li>
169<li><a href="#n_api_napi_extended_error_info">napi_extended_error_info</a></li>
170<li><a href="#n_api_napi_env">napi_env</a></li>
171<li><a href="#n_api_napi_value">napi_value</a></li>
172<li><a href="#n_api_napi_threadsafe_function">napi_threadsafe_function</a></li>
173<li><a href="#n_api_napi_threadsafe_function_release_mode">napi_threadsafe_function_release_mode</a></li>
174<li><a href="#n_api_napi_threadsafe_function_call_mode">napi_threadsafe_function_call_mode</a></li>
175<li><a href="#n_api_node_api_memory_management_types">Node-API memory management types</a>
176<ul>
177<li><a href="#n_api_napi_handle_scope">napi_handle_scope</a></li>
178<li><a href="#n_api_napi_escapable_handle_scope">napi_escapable_handle_scope</a></li>
179<li><a href="#n_api_napi_ref">napi_ref</a></li>
180<li><a href="#n_api_napi_type_tag">napi_type_tag</a></li>
181<li><a href="#n_api_napi_async_cleanup_hook_handle">napi_async_cleanup_hook_handle</a></li>
182</ul>
183</li>
184<li><a href="#n_api_node_api_callback_types">Node-API callback types</a>
185<ul>
186<li><a href="#n_api_napi_callback_info">napi_callback_info</a></li>
187<li><a href="#n_api_napi_callback">napi_callback</a></li>
188<li><a href="#n_api_napi_finalize">napi_finalize</a></li>
189<li><a href="#n_api_napi_async_execute_callback">napi_async_execute_callback</a></li>
190<li><a href="#n_api_napi_async_complete_callback">napi_async_complete_callback</a></li>
191<li><a href="#n_api_napi_threadsafe_function_call_js">napi_threadsafe_function_call_js</a></li>
192<li><a href="#n_api_napi_async_cleanup_hook">napi_async_cleanup_hook</a></li>
193</ul>
194</li>
195</ul>
196</li>
197<li><a href="#n_api_error_handling">Error handling</a>
198<ul>
199<li><a href="#n_api_return_values">Return values</a>
200<ul>
201<li><a href="#n_api_napi_get_last_error_info">napi_get_last_error_info</a></li>
202</ul>
203</li>
204<li><a href="#n_api_exceptions">Exceptions</a>
205<ul>
206<li><a href="#n_api_napi_throw">napi_throw</a></li>
207<li><a href="#n_api_napi_throw_error">napi_throw_error</a></li>
208<li><a href="#n_api_napi_throw_type_error">napi_throw_type_error</a></li>
209<li><a href="#n_api_napi_throw_range_error">napi_throw_range_error</a></li>
210<li><a href="#n_api_napi_is_error">napi_is_error</a></li>
211<li><a href="#n_api_napi_create_error">napi_create_error</a></li>
212<li><a href="#n_api_napi_create_type_error">napi_create_type_error</a></li>
213<li><a href="#n_api_napi_create_range_error">napi_create_range_error</a></li>
214<li><a href="#n_api_napi_get_and_clear_last_exception">napi_get_and_clear_last_exception</a></li>
215<li><a href="#n_api_napi_is_exception_pending">napi_is_exception_pending</a></li>
216<li><a href="#n_api_napi_fatal_exception">napi_fatal_exception</a></li>
217</ul>
218</li>
219<li><a href="#n_api_fatal_errors">Fatal errors</a>
220<ul>
221<li><a href="#n_api_napi_fatal_error">napi_fatal_error</a></li>
222</ul>
223</li>
224</ul>
225</li>
226<li><a href="#n_api_object_lifetime_management">Object lifetime management</a>
227<ul>
228<li><a href="#n_api_making_handle_lifespan_shorter_than_that_of_the_native_method">Making handle lifespan shorter than that of the native method</a>
229<ul>
230<li><a href="#n_api_napi_open_handle_scope">napi_open_handle_scope</a></li>
231<li><a href="#n_api_napi_close_handle_scope">napi_close_handle_scope</a></li>
232<li><a href="#n_api_napi_open_escapable_handle_scope">napi_open_escapable_handle_scope</a></li>
233<li><a href="#n_api_napi_close_escapable_handle_scope">napi_close_escapable_handle_scope</a></li>
234<li><a href="#n_api_napi_escape_handle">napi_escape_handle</a></li>
235</ul>
236</li>
237<li><a href="#n_api_references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method">References to objects with a lifespan longer than that of the native method</a>
238<ul>
239<li><a href="#n_api_napi_create_reference">napi_create_reference</a></li>
240<li><a href="#n_api_napi_delete_reference">napi_delete_reference</a></li>
241<li><a href="#n_api_napi_reference_ref">napi_reference_ref</a></li>
242<li><a href="#n_api_napi_reference_unref">napi_reference_unref</a></li>
243<li><a href="#n_api_napi_get_reference_value">napi_get_reference_value</a></li>
244</ul>
245</li>
246<li><a href="#n_api_cleanup_on_exit_of_the_current_node_js_instance">Cleanup on exit of the current Node.js instance</a>
247<ul>
248<li><a href="#n_api_napi_add_env_cleanup_hook">napi_add_env_cleanup_hook</a></li>
249<li><a href="#n_api_napi_remove_env_cleanup_hook">napi_remove_env_cleanup_hook</a></li>
250<li><a href="#n_api_napi_add_async_cleanup_hook">napi_add_async_cleanup_hook</a></li>
251<li><a href="#n_api_napi_remove_async_cleanup_hook">napi_remove_async_cleanup_hook</a></li>
252</ul>
253</li>
254</ul>
255</li>
256<li><a href="#n_api_module_registration">Module registration</a></li>
257<li><a href="#n_api_working_with_javascript_values">Working with JavaScript values</a>
258<ul>
259<li><a href="#n_api_enum_types">Enum types</a>
260<ul>
261<li><a href="#n_api_napi_key_collection_mode">napi_key_collection_mode</a></li>
262<li><a href="#n_api_napi_key_filter">napi_key_filter</a></li>
263<li><a href="#n_api_napi_key_conversion">napi_key_conversion</a></li>
264<li><a href="#n_api_napi_valuetype">napi_valuetype</a></li>
265<li><a href="#n_api_napi_typedarray_type">napi_typedarray_type</a></li>
266</ul>
267</li>
268<li><a href="#n_api_object_creation_functions">Object creation functions</a>
269<ul>
270<li><a href="#n_api_napi_create_array">napi_create_array</a></li>
271<li><a href="#n_api_napi_create_array_with_length">napi_create_array_with_length</a></li>
272<li><a href="#n_api_napi_create_arraybuffer">napi_create_arraybuffer</a></li>
273<li><a href="#n_api_napi_create_buffer">napi_create_buffer</a></li>
274<li><a href="#n_api_napi_create_buffer_copy">napi_create_buffer_copy</a></li>
275<li><a href="#n_api_napi_create_date">napi_create_date</a></li>
276<li><a href="#n_api_napi_create_external">napi_create_external</a></li>
277<li><a href="#n_api_napi_create_external_arraybuffer">napi_create_external_arraybuffer</a></li>
278<li><a href="#n_api_napi_create_external_buffer">napi_create_external_buffer</a></li>
279<li><a href="#n_api_napi_create_object">napi_create_object</a></li>
280<li><a href="#n_api_napi_create_symbol">napi_create_symbol</a></li>
281<li><a href="#n_api_napi_create_typedarray">napi_create_typedarray</a></li>
282<li><a href="#n_api_napi_create_dataview">napi_create_dataview</a></li>
283</ul>
284</li>
285<li><a href="#n_api_functions_to_convert_from_c_types_to_node_api">Functions to convert from C types to Node-API</a>
286<ul>
287<li><a href="#n_api_napi_create_int32">napi_create_int32</a></li>
288<li><a href="#n_api_napi_create_uint32">napi_create_uint32</a></li>
289<li><a href="#n_api_napi_create_int64">napi_create_int64</a></li>
290<li><a href="#n_api_napi_create_double">napi_create_double</a></li>
291<li><a href="#n_api_napi_create_bigint_int64">napi_create_bigint_int64</a></li>
292<li><a href="#n_api_napi_create_bigint_uint64">napi_create_bigint_uint64</a></li>
293<li><a href="#n_api_napi_create_bigint_words">napi_create_bigint_words</a></li>
294<li><a href="#n_api_napi_create_string_latin1">napi_create_string_latin1</a></li>
295<li><a href="#n_api_napi_create_string_utf16">napi_create_string_utf16</a></li>
296<li><a href="#n_api_napi_create_string_utf8">napi_create_string_utf8</a></li>
297</ul>
298</li>
299<li><a href="#n_api_functions_to_convert_from_node_api_to_c_types">Functions to convert from Node-API to C types</a>
300<ul>
301<li><a href="#n_api_napi_get_array_length">napi_get_array_length</a></li>
302<li><a href="#n_api_napi_get_arraybuffer_info">napi_get_arraybuffer_info</a></li>
303<li><a href="#n_api_napi_get_buffer_info">napi_get_buffer_info</a></li>
304<li><a href="#n_api_napi_get_prototype">napi_get_prototype</a></li>
305<li><a href="#n_api_napi_get_typedarray_info">napi_get_typedarray_info</a></li>
306<li><a href="#n_api_napi_get_dataview_info">napi_get_dataview_info</a></li>
307<li><a href="#n_api_napi_get_date_value">napi_get_date_value</a></li>
308<li><a href="#n_api_napi_get_value_bool">napi_get_value_bool</a></li>
309<li><a href="#n_api_napi_get_value_double">napi_get_value_double</a></li>
310<li><a href="#n_api_napi_get_value_bigint_int64">napi_get_value_bigint_int64</a></li>
311<li><a href="#n_api_napi_get_value_bigint_uint64">napi_get_value_bigint_uint64</a></li>
312<li><a href="#n_api_napi_get_value_bigint_words">napi_get_value_bigint_words</a></li>
313<li><a href="#n_api_napi_get_value_external">napi_get_value_external</a></li>
314<li><a href="#n_api_napi_get_value_int32">napi_get_value_int32</a></li>
315<li><a href="#n_api_napi_get_value_int64">napi_get_value_int64</a></li>
316<li><a href="#n_api_napi_get_value_string_latin1">napi_get_value_string_latin1</a></li>
317<li><a href="#n_api_napi_get_value_string_utf8">napi_get_value_string_utf8</a></li>
318<li><a href="#n_api_napi_get_value_string_utf16">napi_get_value_string_utf16</a></li>
319<li><a href="#n_api_napi_get_value_uint32">napi_get_value_uint32</a></li>
320</ul>
321</li>
322<li><a href="#n_api_functions_to_get_global_instances">Functions to get global instances</a>
323<ul>
324<li><a href="#n_api_napi_get_boolean">napi_get_boolean</a></li>
325<li><a href="#n_api_napi_get_global">napi_get_global</a></li>
326<li><a href="#n_api_napi_get_null">napi_get_null</a></li>
327<li><a href="#n_api_napi_get_undefined">napi_get_undefined</a></li>
328</ul>
329</li>
330</ul>
331</li>
332<li><a href="#n_api_working_with_javascript_values_and_abstract_operations">Working with JavaScript values and abstract operations</a>
333<ul>
334<li><a href="#n_api_napi_coerce_to_bool">napi_coerce_to_bool</a></li>
335<li><a href="#n_api_napi_coerce_to_number">napi_coerce_to_number</a></li>
336<li><a href="#n_api_napi_coerce_to_object">napi_coerce_to_object</a></li>
337<li><a href="#n_api_napi_coerce_to_string">napi_coerce_to_string</a></li>
338<li><a href="#n_api_napi_typeof">napi_typeof</a></li>
339<li><a href="#n_api_napi_instanceof">napi_instanceof</a></li>
340<li><a href="#n_api_napi_is_array">napi_is_array</a></li>
341<li><a href="#n_api_napi_is_arraybuffer">napi_is_arraybuffer</a></li>
342<li><a href="#n_api_napi_is_buffer">napi_is_buffer</a></li>
343<li><a href="#n_api_napi_is_date">napi_is_date</a></li>
344<li><a href="#n_api_napi_is_error_1">napi_is_error</a></li>
345<li><a href="#n_api_napi_is_typedarray">napi_is_typedarray</a></li>
346<li><a href="#n_api_napi_is_dataview">napi_is_dataview</a></li>
347<li><a href="#n_api_napi_strict_equals">napi_strict_equals</a></li>
348<li><a href="#n_api_napi_detach_arraybuffer">napi_detach_arraybuffer</a></li>
349<li><a href="#n_api_napi_is_detached_arraybuffer">napi_is_detached_arraybuffer</a></li>
350</ul>
351</li>
352<li><a href="#n_api_working_with_javascript_properties">Working with JavaScript properties</a>
353<ul>
354<li><a href="#n_api_structures">Structures</a>
355<ul>
356<li><a href="#n_api_napi_property_attributes">napi_property_attributes</a></li>
357<li><a href="#n_api_napi_property_descriptor">napi_property_descriptor</a></li>
358</ul>
359</li>
360<li><a href="#n_api_functions">Functions</a>
361<ul>
362<li><a href="#n_api_napi_get_property_names">napi_get_property_names</a></li>
363<li><a href="#n_api_napi_get_all_property_names">napi_get_all_property_names</a></li>
364<li><a href="#n_api_napi_set_property">napi_set_property</a></li>
365<li><a href="#n_api_napi_get_property">napi_get_property</a></li>
366<li><a href="#n_api_napi_has_property">napi_has_property</a></li>
367<li><a href="#n_api_napi_delete_property">napi_delete_property</a></li>
368<li><a href="#n_api_napi_has_own_property">napi_has_own_property</a></li>
369<li><a href="#n_api_napi_set_named_property">napi_set_named_property</a></li>
370<li><a href="#n_api_napi_get_named_property">napi_get_named_property</a></li>
371<li><a href="#n_api_napi_has_named_property">napi_has_named_property</a></li>
372<li><a href="#n_api_napi_set_element">napi_set_element</a></li>
373<li><a href="#n_api_napi_get_element">napi_get_element</a></li>
374<li><a href="#n_api_napi_has_element">napi_has_element</a></li>
375<li><a href="#n_api_napi_delete_element">napi_delete_element</a></li>
376<li><a href="#n_api_napi_define_properties">napi_define_properties</a></li>
377<li><a href="#n_api_napi_object_freeze">napi_object_freeze</a></li>
378<li><a href="#n_api_napi_object_seal">napi_object_seal</a></li>
379</ul>
380</li>
381</ul>
382</li>
383<li><a href="#n_api_working_with_javascript_functions">Working with JavaScript functions</a>
384<ul>
385<li><a href="#n_api_napi_call_function">napi_call_function</a></li>
386<li><a href="#n_api_napi_create_function">napi_create_function</a></li>
387<li><a href="#n_api_napi_get_cb_info">napi_get_cb_info</a></li>
388<li><a href="#n_api_napi_get_new_target">napi_get_new_target</a></li>
389<li><a href="#n_api_napi_new_instance">napi_new_instance</a></li>
390</ul>
391</li>
392<li><a href="#n_api_object_wrap">Object wrap</a>
393<ul>
394<li><a href="#n_api_napi_define_class">napi_define_class</a></li>
395<li><a href="#n_api_napi_wrap">napi_wrap</a></li>
396<li><a href="#n_api_napi_unwrap">napi_unwrap</a></li>
397<li><a href="#n_api_napi_remove_wrap">napi_remove_wrap</a></li>
398<li><a href="#n_api_napi_type_tag_object">napi_type_tag_object</a></li>
399<li><a href="#n_api_napi_check_object_type_tag">napi_check_object_type_tag</a></li>
400<li><a href="#n_api_napi_add_finalizer">napi_add_finalizer</a></li>
401</ul>
402</li>
403<li><a href="#n_api_simple_asynchronous_operations">Simple asynchronous operations</a>
404<ul>
405<li><a href="#n_api_napi_create_async_work">napi_create_async_work</a></li>
406<li><a href="#n_api_napi_delete_async_work">napi_delete_async_work</a></li>
407<li><a href="#n_api_napi_queue_async_work">napi_queue_async_work</a></li>
408<li><a href="#n_api_napi_cancel_async_work">napi_cancel_async_work</a></li>
409</ul>
410</li>
411<li><a href="#n_api_custom_asynchronous_operations">Custom asynchronous operations</a>
412<ul>
413<li><a href="#n_api_napi_async_init">napi_async_init</a></li>
414<li><a href="#n_api_napi_async_destroy">napi_async_destroy</a></li>
415<li><a href="#n_api_napi_make_callback">napi_make_callback</a></li>
416<li><a href="#n_api_napi_open_callback_scope">napi_open_callback_scope</a></li>
417<li><a href="#n_api_napi_close_callback_scope">napi_close_callback_scope</a></li>
418</ul>
419</li>
420<li><a href="#n_api_version_management">Version management</a>
421<ul>
422<li><a href="#n_api_napi_get_node_version">napi_get_node_version</a></li>
423<li><a href="#n_api_napi_get_version">napi_get_version</a></li>
424</ul>
425</li>
426<li><a href="#n_api_memory_management">Memory management</a>
427<ul>
428<li><a href="#n_api_napi_adjust_external_memory">napi_adjust_external_memory</a></li>
429</ul>
430</li>
431<li><a href="#n_api_promises">Promises</a>
432<ul>
433<li><a href="#n_api_napi_create_promise">napi_create_promise</a></li>
434<li><a href="#n_api_napi_resolve_deferred">napi_resolve_deferred</a></li>
435<li><a href="#n_api_napi_reject_deferred">napi_reject_deferred</a></li>
436<li><a href="#n_api_napi_is_promise">napi_is_promise</a></li>
437</ul>
438</li>
439<li><a href="#n_api_script_execution">Script execution</a>
440<ul>
441<li><a href="#n_api_napi_run_script">napi_run_script</a></li>
442</ul>
443</li>
444<li><a href="#n_api_libuv_event_loop">libuv event loop</a>
445<ul>
446<li><a href="#n_api_napi_get_uv_event_loop">napi_get_uv_event_loop</a></li>
447</ul>
448</li>
449<li><a href="#n_api_asynchronous_thread_safe_function_calls">Asynchronous thread-safe function calls</a>
450<ul>
451<li><a href="#n_api_calling_a_thread_safe_function">Calling a thread-safe function</a></li>
452<li><a href="#n_api_reference_counting_of_thread_safe_functions">Reference counting of thread-safe functions</a></li>
453<li><a href="#n_api_deciding_whether_to_keep_the_process_running">Deciding whether to keep the process running</a></li>
454<li><a href="#n_api_napi_create_threadsafe_function">napi_create_threadsafe_function</a></li>
455<li><a href="#n_api_napi_get_threadsafe_function_context">napi_get_threadsafe_function_context</a></li>
456<li><a href="#n_api_napi_call_threadsafe_function">napi_call_threadsafe_function</a></li>
457<li><a href="#n_api_napi_acquire_threadsafe_function">napi_acquire_threadsafe_function</a></li>
458<li><a href="#n_api_napi_release_threadsafe_function">napi_release_threadsafe_function</a></li>
459<li><a href="#n_api_napi_ref_threadsafe_function">napi_ref_threadsafe_function</a></li>
460<li><a href="#n_api_napi_unref_threadsafe_function">napi_unref_threadsafe_function</a></li>
461</ul>
462</li>
463<li><a href="#n_api_miscellaneous_utilities">Miscellaneous utilities</a></li>
464<li><span class="stability_1"><a href="#n_api_node_api_get_module_file_name">node_api_get_module_file_name</a></span></li>
465</ul>
466</li>
467</ul></details>
468
469      <div id="apicontent">
470        <h2>Node-API<span><a class="mark" href="#n_api_node_api" id="n_api_node_api">#</a></span></h2>
471
472
473<p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
474<p>Node-API (formerly N-API) is an API for building native Addons. It is
475independent from the underlying JavaScript runtime (for example, V8) and is
476maintained as part of Node.js itself. This API will be Application Binary
477Interface (ABI) stable across versions of Node.js. It is intended to insulate
478addons from changes in the underlying JavaScript engine and allow modules
479compiled for one major version to run on later major versions of Node.js without
480recompilation. The <a href="https://nodejs.org/en/docs/guides/abi-stability/">ABI Stability</a> guide provides a more in-depth explanation.</p>
481<p>Addons are built/packaged with the same approach/tools outlined in the section
482titled <a href="addons.html">C++ Addons</a>. The only difference is the set of APIs that are used by
483the native code. Instead of using the V8 or <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a>
484APIs, the functions available in Node-API are used.</p>
485<p>APIs exposed by Node-API are generally used to create and manipulate
486JavaScript values. Concepts and operations generally map to ideas specified
487in the ECMA-262 Language Specification. The APIs have the following
488properties:</p>
489<ul>
490<li>All Node-API calls return a status code of type <code>napi_status</code>. This
491status indicates whether the API call succeeded or failed.</li>
492<li>The API's return value is passed via an out parameter.</li>
493<li>All JavaScript values are abstracted behind an opaque type named
494<code>napi_value</code>.</li>
495<li>In case of an error status code, additional information can be obtained
496using <code>napi_get_last_error_info</code>. More information can be found in the error
497handling section <a href="#n_api_error_handling">Error handling</a>.</li>
498</ul>
499<p>Node-API is a C API that ensures ABI stability across Node.js versions
500and different compiler levels. A C++ API can be easier to use.
501To support using C++, the project maintains a
502C++ wrapper module called <a href="https://github.com/nodejs/node-addon-api"><code>node-addon-api</code></a>.
503This wrapper provides an inlineable C++ API. Binaries built
504with <code>node-addon-api</code> will depend on the symbols for the Node-API C-based
505functions exported by Node.js. <code>node-addon-api</code> is a more
506efficient way to write code that calls Node-API. Take, for example, the
507following <code>node-addon-api</code> code. The first section shows the
508<code>node-addon-api</code> code and the second section shows what actually gets
509used in the addon.</p>
510<pre><code class="language-cpp">Object obj = Object::<span class="hljs-built_in">New</span>(env);
511obj[<span class="hljs-string">"foo"</span>] = String::<span class="hljs-built_in">New</span>(env, <span class="hljs-string">"bar"</span>);</code></pre>
512<pre><code class="language-cpp">napi_status status;
513napi_value object, string;
514status = <span class="hljs-built_in">napi_create_object</span>(env, &#x26;object);
515<span class="hljs-keyword">if</span> (status != napi_ok) {
516  <span class="hljs-built_in">napi_throw_error</span>(env, ...);
517  <span class="hljs-keyword">return</span>;
518}
519
520status = <span class="hljs-built_in">napi_create_string_utf8</span>(env, <span class="hljs-string">"bar"</span>, NAPI_AUTO_LENGTH, &#x26;string);
521<span class="hljs-keyword">if</span> (status != napi_ok) {
522  <span class="hljs-built_in">napi_throw_error</span>(env, ...);
523  <span class="hljs-keyword">return</span>;
524}
525
526status = <span class="hljs-built_in">napi_set_named_property</span>(env, object, <span class="hljs-string">"foo"</span>, string);
527<span class="hljs-keyword">if</span> (status != napi_ok) {
528  <span class="hljs-built_in">napi_throw_error</span>(env, ...);
529  <span class="hljs-keyword">return</span>;
530}</code></pre>
531<p>The end result is that the addon only uses the exported C APIs. As a result,
532it still gets the benefits of the ABI stability provided by the C API.</p>
533<p>When using <code>node-addon-api</code> instead of the C APIs, start with the API <a href="https://github.com/nodejs/node-addon-api#api-documentation">docs</a>
534for <code>node-addon-api</code>.</p>
535<p>The <a href="https://nodejs.github.io/node-addon-examples/">Node-API Resource</a> offers
536an excellent orientation and tips for developers just getting started with
537Node-API and <code>node-addon-api</code>.</p>
538<section><h3>Implications of ABI stability<span><a class="mark" href="#n_api_implications_of_abi_stability" id="n_api_implications_of_abi_stability">#</a></span></h3>
539<p>Although Node-API provides an ABI stability guarantee, other parts of Node.js do
540not, and any external libraries used from the addon may not. In particular,
541none of the following APIs provide an ABI stability guarantee across major
542versions:</p>
543<ul>
544<li>
545<p>the Node.js C++ APIs available via any of</p>
546<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
547<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_buffer.h></span></span>
548<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_version.h></span></span>
549<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_object_wrap.h></span></span></code></pre>
550</li>
551<li>
552<p>the libuv APIs which are also included with Node.js and available via</p>
553<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;uv.h></span></span></code></pre>
554</li>
555<li>
556<p>the V8 API available via</p>
557<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;v8.h></span></span></code></pre>
558</li>
559</ul>
560<p>Thus, for an addon to remain ABI-compatible across Node.js major versions, it
561must use Node-API exclusively by restricting itself to using</p>
562<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span></code></pre>
563<p>and by checking, for all external libraries that it uses, that the external
564library makes ABI stability guarantees similar to Node-API.</p>
565</section><section><h3>Building<span><a class="mark" href="#n_api_building" id="n_api_building">#</a></span></h3>
566<p>Unlike modules written in JavaScript, developing and deploying Node.js
567native addons using Node-API requires an additional set of tools. Besides the
568basic tools required to develop for Node.js, the native addon developer
569requires a toolchain that can compile C and C++ code into a binary. In
570addition, depending upon how the native addon is deployed, the <em>user</em> of
571the native addon will also need to have a C/C++ toolchain installed.</p>
572<p>For Linux developers, the necessary C/C++ toolchain packages are readily
573available. <a href="https://gcc.gnu.org">GCC</a> is widely used in the Node.js community to build and
574test across a variety of platforms. For many developers, the <a href="https://llvm.org">LLVM</a>
575compiler infrastructure is also a good choice.</p>
576<p>For Mac developers, <a href="https://developer.apple.com/xcode/">Xcode</a> offers all the required compiler tools.
577However, it is not necessary to install the entire Xcode IDE. The following
578command installs the necessary toolchain:</p>
579<pre><code class="language-bash">xcode-select --install</code></pre>
580<p>For Windows developers, <a href="https://visualstudio.microsoft.com">Visual Studio</a> offers all the required compiler
581tools. However, it is not necessary to install the entire Visual Studio
582IDE. The following command installs the necessary toolchain:</p>
583<pre><code class="language-bash">npm install --global windows-build-tools</code></pre>
584<p>The sections below describe the additional tools available for developing
585and deploying Node.js native addons.</p>
586<h4>Build tools<span><a class="mark" href="#n_api_build_tools" id="n_api_build_tools">#</a></span></h4>
587<p>Both the tools listed here require that <em>users</em> of the native
588addon have a C/C++ toolchain installed in order to successfully install
589the native addon.</p>
590<h5>node-gyp<span><a class="mark" href="#n_api_node_gyp" id="n_api_node_gyp">#</a></span></h5>
591<p><a href="https://github.com/nodejs/node-gyp">node-gyp</a> is a build system based on the <a href="https://github.com/nodejs/gyp-next">gyp-next</a> fork of
592Google's <a href="https://gyp.gsrc.io">GYP</a> tool and comes bundled with npm. GYP, and therefore node-gyp,
593requires that Python be installed.</p>
594<p>Historically, node-gyp has been the tool of choice for building native
595addons. It has widespread adoption and documentation. However, some
596developers have run into limitations in node-gyp.</p>
597<h5>CMake.js<span><a class="mark" href="#n_api_cmake_js" id="n_api_cmake_js">#</a></span></h5>
598<p><a href="https://github.com/cmake-js/cmake-js">CMake.js</a> is an alternative build system based on <a href="https://cmake.org">CMake</a>.</p>
599<p>CMake.js is a good choice for projects that already use CMake or for
600developers affected by limitations in node-gyp.</p>
601<h4>Uploading precompiled binaries<span><a class="mark" href="#n_api_uploading_precompiled_binaries" id="n_api_uploading_precompiled_binaries">#</a></span></h4>
602<p>The three tools listed here permit native addon developers and maintainers
603to create and upload binaries to public or private servers. These tools are
604typically integrated with CI/CD build systems like <a href="https://travis-ci.org">Travis CI</a> and
605<a href="https://www.appveyor.com">AppVeyor</a> to build and upload binaries for a variety of platforms and
606architectures. These binaries are then available for download by users who
607do not need to have a C/C++ toolchain installed.</p>
608<h5>node-pre-gyp<span><a class="mark" href="#n_api_node_pre_gyp" id="n_api_node_pre_gyp">#</a></span></h5>
609<p><a href="https://github.com/mapbox/node-pre-gyp">node-pre-gyp</a> is a tool based on node-gyp that adds the ability to
610upload binaries to a server of the developer's choice. node-pre-gyp has
611particularly good support for uploading binaries to Amazon S3.</p>
612<h5>prebuild<span><a class="mark" href="#n_api_prebuild" id="n_api_prebuild">#</a></span></h5>
613<p><a href="https://github.com/prebuild/prebuild">prebuild</a> is a tool that supports builds using either node-gyp or
614CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild
615uploads binaries only to <a href="https://help.github.com/en/github/administering-a-repository/about-releases">GitHub releases</a>. prebuild is a good choice for
616GitHub projects using CMake.js.</p>
617<h5>prebuildify<span><a class="mark" href="#n_api_prebuildify" id="n_api_prebuildify">#</a></span></h5>
618<p><a href="https://github.com/prebuild/prebuildify">prebuildify</a> is a tool based on node-gyp. The advantage of prebuildify is
619that the built binaries are bundled with the native module when it's
620uploaded to npm. The binaries are downloaded from npm and are immediately
621available to the module user when the native module is installed.</p>
622</section><section><h3>Usage<span><a class="mark" href="#n_api_usage" id="n_api_usage">#</a></span></h3>
623<p>In order to use the Node-API functions, include the file <a href="https://github.com/nodejs/node/blob/HEAD/src/node_api.h"><code>node_api.h</code></a> which
624is located in the src directory in the node development tree:</p>
625<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span></code></pre>
626<p>This will opt into the default <code>NAPI_VERSION</code> for the given release of Node.js.
627In order to ensure compatibility with specific versions of Node-API, the version
628can be specified explicitly when including the header:</p>
629<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NAPI_VERSION 3</span>
630<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span></code></pre>
631<p>This restricts the Node-API surface to just the functionality that was available
632in the specified (and earlier) versions.</p>
633<p>Some of the Node-API surface is experimental and requires explicit opt-in:</p>
634<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NAPI_EXPERIMENTAL</span>
635<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span></code></pre>
636<p>In this case the entire API surface, including any experimental APIs, will be
637available to the module code.</p>
638</section><section><h3>Node-API version matrix<span><a class="mark" href="#n_api_node_api_version_matrix" id="n_api_node_api_version_matrix">#</a></span></h3>
639<p>Node-API versions are additive and versioned independently from Node.js.
640Version 4 is an extension to version 3 in that it has all of the APIs
641from version 3 with some additions. This means that it is not necessary
642to recompile for new versions of Node.js which are
643listed as supporting a later version.</p>
644<!-- For accessibility purposes, this table needs row headers. That means we
645     can't do it in markdown. Hence, the raw HTML. -->
646<table>
647  <tbody><tr>
648    <td></td>
649    <th scope="col">1</th>
650    <th scope="col">2</th>
651    <th scope="col">3</th>
652  </tr>
653  <tr>
654    <th scope="row">v6.x</th>
655    <td></td>
656    <td></td>
657    <td>v6.14.2*</td>
658  </tr>
659  <tr>
660    <th scope="row">v8.x</th>
661    <td>v8.6.0**</td>
662    <td>v8.10.0*</td>
663    <td>v8.11.2</td>
664  </tr>
665  <tr>
666    <th scope="row">v9.x</th>
667    <td>v9.0.0*</td>
668    <td>v9.3.0*</td>
669    <td>v9.11.0*</td>
670  </tr>
671  <tr>
672    <th scope="row">≥ v10.x</th>
673    <td>all releases</td>
674    <td>all releases</td>
675    <td>all releases</td>
676  </tr>
677</tbody></table>
678<table>
679  <tbody><tr>
680    <td></td>
681    <th scope="col">4</th>
682    <th scope="col">5</th>
683    <th scope="col">6</th>
684    <th scope="col">7</th>
685    <th scope="col">8</th>
686  </tr>
687  <tr>
688    <th scope="row">v10.x</th>
689    <td>v10.16.0</td>
690    <td>v10.17.0</td>
691    <td>v10.20.0</td>
692    <td>v10.23.0</td>
693    <td></td>
694  </tr>
695  <tr>
696    <th scope="row">v11.x</th>
697    <td>v11.8.0</td>
698    <td></td>
699    <td></td>
700    <td></td>
701    <td></td>
702  </tr>
703  <tr>
704    <th scope="row">v12.x</th>
705    <td>v12.0.0</td>
706    <td>v12.11.0</td>
707    <td>v12.17.0</td>
708    <td>v12.19.0</td>
709    <td>v12.22.0</td>
710  </tr>
711  <tr>
712    <th scope="row">v13.x</th>
713    <td>v13.0.0</td>
714    <td>v13.0.0</td>
715    <td></td>
716    <td></td>
717    <td></td>
718  </tr>
719  <tr>
720    <th scope="row">v14.x</th>
721    <td>v14.0.0</td>
722    <td>v14.0.0</td>
723    <td>v14.0.0</td>
724    <td>v14.12.0</td>
725    <td>v14.17.0</td>
726  </tr>
727  <tr>
728    <th scope="row">v15.x</th>
729    <td>v15.0.0</td>
730    <td>v15.0.0</td>
731    <td>v15.0.0</td>
732    <td>v15.0.0</td>
733    <td>v15.12.0</td>
734  </tr>
735  <tr>
736    <th scope="row">v16.x</th>
737    <td>v16.0.0</td>
738    <td>v16.0.0</td>
739    <td>v16.0.0</td>
740    <td>v16.0.0</td>
741    <td>v16.0.0</td>
742  </tr>
743</tbody></table>
744<p>* Node-API was experimental.</p>
745<p>** Node.js 8.0.0 included Node-API as experimental. It was released as
746Node-API version 1 but continued to evolve until Node.js 8.6.0. The API is
747different in versions prior to Node.js 8.6.0. We recommend Node-API version 3 or
748later.</p>
749<p>Each API documented for Node-API will have a header named <code>added in:</code>, and APIs
750which are stable will have the additional header <code>Node-API version:</code>.
751APIs are directly usable when using a Node.js version which supports
752the Node-API version shown in <code>Node-API version:</code> or higher.
753When using a Node.js version that does not support the
754<code>Node-API version:</code> listed or if there is no <code>Node-API version:</code> listed,
755then the API will only be available if
756<code>#define NAPI_EXPERIMENTAL</code> precedes the inclusion of <code>node_api.h</code>
757or <code>js_native_api.h</code>. If an API appears not to be available on
758a version of Node.js which is later than the one shown in <code>added in:</code> then
759this is most likely the reason for the apparent absence.</p>
760<p>The Node-APIs associated strictly with accessing ECMAScript features from native
761code can be found separately in <code>js_native_api.h</code> and <code>js_native_api_types.h</code>.
762The APIs defined in these headers are included in <code>node_api.h</code> and
763<code>node_api_types.h</code>. The headers are structured in this way in order to allow
764implementations of Node-API outside of Node.js. For those implementations the
765Node.js specific APIs may not be applicable.</p>
766<p>The Node.js-specific parts of an addon can be separated from the code that
767exposes the actual functionality to the JavaScript environment so that the
768latter may be used with multiple implementations of Node-API. In the example
769below, <code>addon.c</code> and <code>addon.h</code> refer only to <code>js_native_api.h</code>. This ensures
770that <code>addon.c</code> can be reused to compile against either the Node.js
771implementation of Node-API or any implementation of Node-API outside of Node.js.</p>
772<p><code>addon_node.c</code> is a separate file that contains the Node.js specific entry point
773to the addon and which instantiates the addon by calling into <code>addon.c</code> when the
774addon is loaded into a Node.js environment.</p>
775<pre><code class="language-c"><span class="hljs-comment">// addon.h</span>
776<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> _ADDON_H_</span>
777<span class="hljs-meta">#<span class="hljs-keyword">define</span> _ADDON_H_</span>
778<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;js_native_api.h></span></span>
779napi_value <span class="hljs-title function_">create_addon</span><span class="hljs-params">(napi_env env)</span>;
780<span class="hljs-meta">#<span class="hljs-keyword">endif</span>  <span class="hljs-comment">// _ADDON_H_</span></span></code></pre>
781<pre><code class="language-c"><span class="hljs-comment">// addon.c</span>
782<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"addon.h"</span></span>
783
784<span class="hljs-meta">#<span class="hljs-keyword">define</span> NAPI_CALL(env, call)                                      \
785  do {                                                            \
786    napi_status status = (call);                                  \
787    <span class="hljs-keyword">if</span> (status != napi_ok) {                                      \
788      const napi_extended_error_info* error_info = NULL;          \
789      napi_get_last_error_info((env), &#x26;error_info);               \
790      bool is_pending;                                            \
791      napi_is_exception_pending((env), &#x26;is_pending);              \
792      <span class="hljs-keyword">if</span> (!is_pending) {                                          \
793        const char* message = (error_info->error_message == NULL) \
794            ? <span class="hljs-string">"empty error message"</span>                               \
795            : error_info->error_message;                          \
796        napi_throw_error((env), NULL, message);                   \
797        return NULL;                                              \
798      }                                                           \
799    }                                                             \
800  } while(0)</span>
801
802<span class="hljs-keyword">static</span> napi_value
803<span class="hljs-title function_">DoSomethingUseful</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
804  <span class="hljs-comment">// Do something useful.</span>
805  <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
806}
807
808napi_value <span class="hljs-title function_">create_addon</span><span class="hljs-params">(napi_env env)</span> {
809  napi_value result;
810  NAPI_CALL(env, napi_create_object(env, &#x26;result));
811
812  napi_value exported_function;
813  NAPI_CALL(env, napi_create_function(env,
814                                      <span class="hljs-string">"doSomethingUseful"</span>,
815                                      NAPI_AUTO_LENGTH,
816                                      DoSomethingUseful,
817                                      <span class="hljs-literal">NULL</span>,
818                                      &#x26;exported_function));
819
820  NAPI_CALL(env, napi_set_named_property(env,
821                                         result,
822                                         <span class="hljs-string">"doSomethingUseful"</span>,
823                                         exported_function));
824
825  <span class="hljs-keyword">return</span> result;
826}</code></pre>
827<pre><code class="language-c"><span class="hljs-comment">// addon_node.c</span>
828<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span>
829<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"addon.h"</span></span>
830
831NAPI_MODULE_INIT() {
832  <span class="hljs-comment">// This function body is expected to return a `napi_value`.</span>
833  <span class="hljs-comment">// The variables `napi_env env` and `napi_value exports` may be used within</span>
834  <span class="hljs-comment">// the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.</span>
835  <span class="hljs-keyword">return</span> create_addon(env);
836}</code></pre>
837</section><section><h3>Environment life cycle APIs<span><a class="mark" href="#n_api_environment_life_cycle_apis" id="n_api_environment_life_cycle_apis">#</a></span></h3>
838<p><a href="https://tc39.es/ecma262/#sec-agents">Section 8.7</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a> defines the concept
839of an "Agent" as a self-contained environment in which JavaScript code runs.
840Multiple such Agents may be started and terminated either concurrently or in
841sequence by the process.</p>
842<p>A Node.js environment corresponds to an ECMAScript Agent. In the main process,
843an environment is created at startup, and additional environments can be created
844on separate threads to serve as <a href="https://nodejs.org/api/worker_threads.html">worker threads</a>. When Node.js is embedded in
845another application, the main thread of the application may also construct and
846destroy a Node.js environment multiple times during the life cycle of the
847application process such that each Node.js environment created by the
848application may, in turn, during its life cycle create and destroy additional
849environments as worker threads.</p>
850<p>From the perspective of a native addon this means that the bindings it provides
851may be called multiple times, from multiple contexts, and even concurrently from
852multiple threads.</p>
853<p>Native addons may need to allocate global state which they use during
854their entire life cycle such that the state must be unique to each instance of
855the addon.</p>
856<p>To this end, Node-API provides a way to allocate data such that its life cycle
857is tied to the life cycle of the Agent.</p>
858<h4>napi_set_instance_data<span><a class="mark" href="#n_api_napi_set_instance_data" id="n_api_napi_set_instance_data">#</a></span></h4>
859<div class="api_metadata">
860<span>Added in: v12.8.0, v10.20.0</span>
861<span>N-API version: 6</span>
862</div>
863<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_set_instance_data</span><span class="hljs-params">(napi_env env,
864                                   <span class="hljs-type">void</span>* data,
865                                   napi_finalize finalize_cb,
866                                   <span class="hljs-type">void</span>* finalize_hint)</span>;</code></pre>
867<ul>
868<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
869<li><code>[in] data</code>: The data item to make available to bindings of this instance.</li>
870<li><code>[in] finalize_cb</code>: The function to call when the environment is being torn
871down. The function receives <code>data</code> so that it might free it.
872<a href="#n_api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
873<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
874collection.</li>
875</ul>
876<p>Returns <code>napi_ok</code> if the API succeeded.</p>
877<p>This API associates <code>data</code> with the currently running Agent. <code>data</code> can later
878be retrieved using <code>napi_get_instance_data()</code>. Any existing data associated with
879the currently running Agent which was set by means of a previous call to
880<code>napi_set_instance_data()</code> will be overwritten. If a <code>finalize_cb</code> was provided
881by the previous call, it will not be called.</p>
882<h4>napi_get_instance_data<span><a class="mark" href="#n_api_napi_get_instance_data" id="n_api_napi_get_instance_data">#</a></span></h4>
883<div class="api_metadata">
884<span>Added in: v12.8.0, v10.20.0</span>
885<span>N-API version: 6</span>
886</div>
887<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_instance_data</span><span class="hljs-params">(napi_env env,
888                                   <span class="hljs-type">void</span>** data)</span>;</code></pre>
889<ul>
890<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
891<li><code>[out] data</code>: The data item that was previously associated with the currently
892running Agent by a call to <code>napi_set_instance_data()</code>.</li>
893</ul>
894<p>Returns <code>napi_ok</code> if the API succeeded.</p>
895<p>This API retrieves data that was previously associated with the currently
896running Agent via <code>napi_set_instance_data()</code>. If no data is set, the call will
897succeed and <code>data</code> will be set to <code>NULL</code>.</p>
898</section><section><h3>Basic Node-API data types<span><a class="mark" href="#n_api_basic_node_api_data_types" id="n_api_basic_node_api_data_types">#</a></span></h3>
899<p>Node-API exposes the following fundamental datatypes as abstractions that are
900consumed by the various APIs. These APIs should be treated as opaque,
901introspectable only with other Node-API calls.</p>
902<h4>napi_status<span><a class="mark" href="#n_api_napi_status" id="n_api_napi_status">#</a></span></h4>
903<div class="api_metadata">
904<span>Added in: v8.0.0</span>
905<span>N-API version: 1</span>
906</div>
907<p>Integral status code indicating the success or failure of a Node-API call.
908Currently, the following status codes are supported.</p>
909<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
910  napi_ok,
911  napi_invalid_arg,
912  napi_object_expected,
913  napi_string_expected,
914  napi_name_expected,
915  napi_function_expected,
916  napi_number_expected,
917  napi_boolean_expected,
918  napi_array_expected,
919  napi_generic_failure,
920  napi_pending_exception,
921  napi_cancelled,
922  napi_escape_called_twice,
923  napi_handle_scope_mismatch,
924  napi_callback_scope_mismatch,
925  napi_queue_full,
926  napi_closing,
927  napi_bigint_expected,
928  napi_date_expected,
929  napi_arraybuffer_expected,
930  napi_detachable_arraybuffer_expected,
931  napi_would_deadlock,  <span class="hljs-comment">/* unused */</span>
932} napi_status;</code></pre>
933<p>If additional information is required upon an API returning a failed status,
934it can be obtained by calling <code>napi_get_last_error_info</code>.</p>
935<h4>napi_extended_error_info<span><a class="mark" href="#n_api_napi_extended_error_info" id="n_api_napi_extended_error_info">#</a></span></h4>
936<div class="api_metadata">
937<span>Added in: v8.0.0</span>
938<span>N-API version: 1</span>
939</div>
940<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
941  <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* error_message;
942  <span class="hljs-type">void</span>* engine_reserved;
943  <span class="hljs-type">uint32_t</span> engine_error_code;
944  napi_status error_code;
945} napi_extended_error_info;</code></pre>
946<ul>
947<li><code>error_message</code>: UTF8-encoded string containing a VM-neutral description of
948the error.</li>
949<li><code>engine_reserved</code>: Reserved for VM-specific error details. This is currently
950not implemented for any VM.</li>
951<li><code>engine_error_code</code>: VM-specific error code. This is currently
952not implemented for any VM.</li>
953<li><code>error_code</code>: The Node-API status code that originated with the last error.</li>
954</ul>
955<p>See the <a href="#n_api_error_handling">Error handling</a> section for additional information.</p>
956<h4>napi_env<span><a class="mark" href="#n_api_napi_env" id="n_api_napi_env">#</a></span></h4>
957<p><code>napi_env</code> is used to represent a context that the underlying Node-API
958implementation can use to persist VM-specific state. This structure is passed
959to native functions when they're invoked, and it must be passed back when
960making Node-API calls. Specifically, the same <code>napi_env</code> that was passed in when
961the initial native function was called must be passed to any subsequent
962nested Node-API calls. Caching the <code>napi_env</code> for the purpose of general reuse,
963and passing the <code>napi_env</code> between instances of the same addon running on
964different <a href="worker_threads.html#worker_threads_class_worker"><code>Worker</code></a> threads is not allowed. The <code>napi_env</code> becomes invalid
965when an instance of a native addon is unloaded. Notification of this event is
966delivered through the callbacks given to <a href="#n_api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a> and
967<a href="#n_api_napi_set_instance_data"><code>napi_set_instance_data</code></a>.</p>
968<h4>napi_value<span><a class="mark" href="#n_api_napi_value" id="n_api_napi_value">#</a></span></h4>
969<p>This is an opaque pointer that is used to represent a JavaScript value.</p>
970<h4>napi_threadsafe_function<span><a class="mark" href="#n_api_napi_threadsafe_function" id="n_api_napi_threadsafe_function">#</a></span></h4>
971<div class="api_metadata">
972<span>Added in: v10.6.0</span>
973<span>N-API version: 4</span>
974</div>
975<p>This is an opaque pointer that represents a JavaScript function which can be
976called asynchronously from multiple threads via
977<code>napi_call_threadsafe_function()</code>.</p>
978<h4>napi_threadsafe_function_release_mode<span><a class="mark" href="#n_api_napi_threadsafe_function_release_mode" id="n_api_napi_threadsafe_function_release_mode">#</a></span></h4>
979<div class="api_metadata">
980<span>Added in: v10.6.0</span>
981<span>N-API version: 4</span>
982</div>
983<p>A value to be given to <code>napi_release_threadsafe_function()</code> to indicate whether
984the thread-safe function is to be closed immediately (<code>napi_tsfn_abort</code>) or
985merely released (<code>napi_tsfn_release</code>) and thus available for subsequent use via
986<code>napi_acquire_threadsafe_function()</code> and <code>napi_call_threadsafe_function()</code>.</p>
987<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
988  napi_tsfn_release,
989  napi_tsfn_abort
990} napi_threadsafe_function_release_mode;</code></pre>
991<h4>napi_threadsafe_function_call_mode<span><a class="mark" href="#n_api_napi_threadsafe_function_call_mode" id="n_api_napi_threadsafe_function_call_mode">#</a></span></h4>
992<div class="api_metadata">
993<span>Added in: v10.6.0</span>
994<span>N-API version: 4</span>
995</div>
996<p>A value to be given to <code>napi_call_threadsafe_function()</code> to indicate whether
997the call should block whenever the queue associated with the thread-safe
998function is full.</p>
999<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
1000  napi_tsfn_nonblocking,
1001  napi_tsfn_blocking
1002} napi_threadsafe_function_call_mode;</code></pre>
1003<h4>Node-API memory management types<span><a class="mark" href="#n_api_node_api_memory_management_types" id="n_api_node_api_memory_management_types">#</a></span></h4>
1004<h5>napi_handle_scope<span><a class="mark" href="#n_api_napi_handle_scope" id="n_api_napi_handle_scope">#</a></span></h5>
1005<p>This is an abstraction used to control and modify the lifetime of objects
1006created within a particular scope. In general, Node-API values are created
1007within the context of a handle scope. When a native method is called from
1008JavaScript, a default handle scope will exist. If the user does not explicitly
1009create a new handle scope, Node-API values will be created in the default handle
1010scope. For any invocations of code outside the execution of a native method
1011(for instance, during a libuv callback invocation), the module is required to
1012create a scope before invoking any functions that can result in the creation
1013of JavaScript values.</p>
1014<p>Handle scopes are created using <a href="#n_api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and are destroyed
1015using <a href="#n_api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a>. Closing the scope can indicate to the GC
1016that all <code>napi_value</code>s created during the lifetime of the handle scope are no
1017longer referenced from the current stack frame.</p>
1018<p>For more details, review the <a href="#n_api_object_lifetime_management">Object lifetime management</a>.</p>
1019<h5>napi_escapable_handle_scope<span><a class="mark" href="#n_api_napi_escapable_handle_scope" id="n_api_napi_escapable_handle_scope">#</a></span></h5>
1020<div class="api_metadata">
1021<span>Added in: v8.0.0</span>
1022<span>N-API version: 1</span>
1023</div>
1024<p>Escapable handle scopes are a special type of handle scope to return values
1025created within a particular handle scope to a parent scope.</p>
1026<h5>napi_ref<span><a class="mark" href="#n_api_napi_ref" id="n_api_napi_ref">#</a></span></h5>
1027<div class="api_metadata">
1028<span>Added in: v8.0.0</span>
1029<span>N-API version: 1</span>
1030</div>
1031<p>This is the abstraction to use to reference a <code>napi_value</code>. This allows for
1032users to manage the lifetimes of JavaScript values, including defining their
1033minimum lifetimes explicitly.</p>
1034<p>For more details, review the <a href="#n_api_object_lifetime_management">Object lifetime management</a>.</p>
1035<h5>napi_type_tag<span><a class="mark" href="#n_api_napi_type_tag" id="n_api_napi_type_tag">#</a></span></h5>
1036<div class="api_metadata">
1037<span>Added in: v14.8.0, v12.19.0</span>
1038<span>N-API version: 8</span>
1039</div>
1040<p>A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID
1041with which JavaScript objects can be "tagged" in order to ensure that they are
1042of a certain type. This is a stronger check than <a href="#n_api_napi_instanceof"><code>napi_instanceof</code></a>, because
1043the latter can report a false positive if the object's prototype has been
1044manipulated. Type-tagging is most useful in conjunction with <a href="#n_api_napi_wrap"><code>napi_wrap</code></a>
1045because it ensures that the pointer retrieved from a wrapped object can be
1046safely cast to the native type corresponding to the type tag that had been
1047previously applied to the JavaScript object.</p>
1048<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
1049  <span class="hljs-type">uint64_t</span> lower;
1050  <span class="hljs-type">uint64_t</span> upper;
1051} napi_type_tag;</code></pre>
1052<h5>napi_async_cleanup_hook_handle<span><a class="mark" href="#n_api_napi_async_cleanup_hook_handle" id="n_api_napi_async_cleanup_hook_handle">#</a></span></h5>
1053<div class="api_metadata">
1054<span>Added in: v14.10.0</span>
1055</div>
1056<p>An opaque value returned by <a href="#n_api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>. It must be passed
1057to <a href="#n_api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a> when the chain of asynchronous cleanup
1058events completes.</p>
1059<h4>Node-API callback types<span><a class="mark" href="#n_api_node_api_callback_types" id="n_api_node_api_callback_types">#</a></span></h4>
1060<h5>napi_callback_info<span><a class="mark" href="#n_api_napi_callback_info" id="n_api_napi_callback_info">#</a></span></h5>
1061<div class="api_metadata">
1062<span>Added in: v8.0.0</span>
1063<span>N-API version: 1</span>
1064</div>
1065<p>Opaque datatype that is passed to a callback function. It can be used for
1066getting additional information about the context in which the callback was
1067invoked.</p>
1068<h5>napi_callback<span><a class="mark" href="#n_api_napi_callback" id="n_api_napi_callback">#</a></span></h5>
1069<div class="api_metadata">
1070<span>Added in: v8.0.0</span>
1071<span>N-API version: 1</span>
1072</div>
1073<p>Function pointer type for user-provided native functions which are to be
1074exposed to JavaScript via Node-API. Callback functions should satisfy the
1075following signature:</p>
1076<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">napi_value</span> <span class="hljs-params">(*napi_callback)</span><span class="hljs-params">(napi_env, napi_callback_info)</span>;</code></pre>
1077<p>Unless for reasons discussed in <a href="#n_api_object_lifetime_management">Object Lifetime Management</a>, creating a
1078handle and/or callback scope inside a <code>napi_callback</code> is not necessary.</p>
1079<h5>napi_finalize<span><a class="mark" href="#n_api_napi_finalize" id="n_api_napi_finalize">#</a></span></h5>
1080<div class="api_metadata">
1081<span>Added in: v8.0.0</span>
1082<span>N-API version: 1</span>
1083</div>
1084<p>Function pointer type for add-on provided functions that allow the user to be
1085notified when externally-owned data is ready to be cleaned up because the
1086object with which it was associated with, has been garbage-collected. The user
1087must provide a function satisfying the following signature which would get
1088called upon the object's collection. Currently, <code>napi_finalize</code> can be used for
1089finding out when objects that have external data are collected.</p>
1090<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_finalize)</span><span class="hljs-params">(napi_env env,
1091                              <span class="hljs-type">void</span>* finalize_data,
1092                              <span class="hljs-type">void</span>* finalize_hint)</span>;</code></pre>
1093<p>Unless for reasons discussed in <a href="#n_api_object_lifetime_management">Object Lifetime Management</a>, creating a
1094handle and/or callback scope inside the function body is not necessary.</p>
1095<h5>napi_async_execute_callback<span><a class="mark" href="#n_api_napi_async_execute_callback" id="n_api_napi_async_execute_callback">#</a></span></h5>
1096<div class="api_metadata">
1097<span>Added in: v8.0.0</span>
1098<span>N-API version: 1</span>
1099</div>
1100<p>Function pointer used with functions that support asynchronous
1101operations. Callback functions must satisfy the following signature:</p>
1102<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_execute_callback)</span><span class="hljs-params">(napi_env env, <span class="hljs-type">void</span>* data)</span>;</code></pre>
1103<p>Implementations of this function must avoid making Node-API calls that execute
1104JavaScript or interact with JavaScript objects. Node-API calls should be in the
1105<code>napi_async_complete_callback</code> instead. Do not use the <code>napi_env</code> parameter as
1106it will likely result in execution of JavaScript.</p>
1107<h5>napi_async_complete_callback<span><a class="mark" href="#n_api_napi_async_complete_callback" id="n_api_napi_async_complete_callback">#</a></span></h5>
1108<div class="api_metadata">
1109<span>Added in: v8.0.0</span>
1110<span>N-API version: 1</span>
1111</div>
1112<p>Function pointer used with functions that support asynchronous
1113operations. Callback functions must satisfy the following signature:</p>
1114<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_complete_callback)</span><span class="hljs-params">(napi_env env,
1115                                             napi_status status,
1116                                             <span class="hljs-type">void</span>* data)</span>;</code></pre>
1117<p>Unless for reasons discussed in <a href="#n_api_object_lifetime_management">Object Lifetime Management</a>, creating a
1118handle and/or callback scope inside the function body is not necessary.</p>
1119<h5>napi_threadsafe_function_call_js<span><a class="mark" href="#n_api_napi_threadsafe_function_call_js" id="n_api_napi_threadsafe_function_call_js">#</a></span></h5>
1120<div class="api_metadata">
1121<span>Added in: v10.6.0</span>
1122<span>N-API version: 4</span>
1123</div>
1124<p>Function pointer used with asynchronous thread-safe function calls. The callback
1125will be called on the main thread. Its purpose is to use a data item arriving
1126via the queue from one of the secondary threads to construct the parameters
1127necessary for a call into JavaScript, usually via <code>napi_call_function</code>, and then
1128make the call into JavaScript.</p>
1129<p>The data arriving from the secondary thread via the queue is given in the <code>data</code>
1130parameter and the JavaScript function to call is given in the <code>js_callback</code>
1131parameter.</p>
1132<p>Node-API sets up the environment prior to calling this callback, so it is
1133sufficient to call the JavaScript function via <code>napi_call_function</code> rather than
1134via <code>napi_make_callback</code>.</p>
1135<p>Callback functions must satisfy the following signature:</p>
1136<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_threadsafe_function_call_js)</span><span class="hljs-params">(napi_env env,
1137                                                 napi_value js_callback,
1138                                                 <span class="hljs-type">void</span>* context,
1139                                                 <span class="hljs-type">void</span>* data)</span>;</code></pre>
1140<ul>
1141<li><code>[in] env</code>: The environment to use for API calls, or <code>NULL</code> if the thread-safe
1142function is being torn down and <code>data</code> may need to be freed.</li>
1143<li><code>[in] js_callback</code>: The JavaScript function to call, or <code>NULL</code> if the
1144thread-safe function is being torn down and <code>data</code> may need to be freed. It
1145may also be <code>NULL</code> if the thread-safe function was created without
1146<code>js_callback</code>.</li>
1147<li><code>[in] context</code>: The optional data with which the thread-safe function was
1148created.</li>
1149<li><code>[in] data</code>: Data created by the secondary thread. It is the responsibility of
1150the callback to convert this native data to JavaScript values (with Node-API
1151functions) that can be passed as parameters when <code>js_callback</code> is invoked.
1152This pointer is managed entirely by the threads and this callback. Thus this
1153callback should free the data.</li>
1154</ul>
1155<p>Unless for reasons discussed in <a href="#n_api_object_lifetime_management">Object Lifetime Management</a>, creating a
1156handle and/or callback scope inside the function body is not necessary.</p>
1157<h5>napi_async_cleanup_hook<span><a class="mark" href="#n_api_napi_async_cleanup_hook" id="n_api_napi_async_cleanup_hook">#</a></span></h5>
1158<div class="api_metadata">
1159<span>Added in: v14.10.0</span>
1160</div>
1161<p>Function pointer used with <a href="#n_api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>. It will be called
1162when the environment is being torn down.</p>
1163<p>Callback functions must satisfy the following signature:</p>
1164<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_cleanup_hook)</span><span class="hljs-params">(napi_async_cleanup_hook_handle handle,
1165                                        <span class="hljs-type">void</span>* data)</span>;</code></pre>
1166<ul>
1167<li><code>[in] handle</code>: The handle that must be passed to
1168<a href="#n_api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a> after completion of the asynchronous
1169cleanup.</li>
1170<li><code>[in] data</code>: The data that was passed to <a href="#n_api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>.</li>
1171</ul>
1172<p>The body of the function should initiate the asynchronous cleanup actions at the
1173end of which <code>handle</code> must be passed in a call to
1174<a href="#n_api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a>.</p>
1175</section><section><h3>Error handling<span><a class="mark" href="#n_api_error_handling" id="n_api_error_handling">#</a></span></h3>
1176<p>Node-API uses both return values and JavaScript exceptions for error handling.
1177The following sections explain the approach for each case.</p>
1178<h4>Return values<span><a class="mark" href="#n_api_return_values" id="n_api_return_values">#</a></span></h4>
1179<p>All of the Node-API functions share the same error handling pattern. The
1180return type of all API functions is <code>napi_status</code>.</p>
1181<p>The return value will be <code>napi_ok</code> if the request was successful and
1182no uncaught JavaScript exception was thrown. If an error occurred AND
1183an exception was thrown, the <code>napi_status</code> value for the error
1184will be returned. If an exception was thrown, and no error occurred,
1185<code>napi_pending_exception</code> will be returned.</p>
1186<p>In cases where a return value other than <code>napi_ok</code> or
1187<code>napi_pending_exception</code> is returned, <a href="#n_api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a>
1188must be called to check if an exception is pending.
1189See the section on exceptions for more details.</p>
1190<p>The full set of possible <code>napi_status</code> values is defined
1191in <code>napi_api_types.h</code>.</p>
1192<p>The <code>napi_status</code> return value provides a VM-independent representation of
1193the error which occurred. In some cases it is useful to be able to get
1194more detailed information, including a string representing the error as well as
1195VM (engine)-specific information.</p>
1196<p>In order to retrieve this information <a href="#n_api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a>
1197is provided which returns a <code>napi_extended_error_info</code> structure.
1198The format of the <code>napi_extended_error_info</code> structure is as follows:</p>
1199<div class="api_metadata">
1200<span>Added in: v8.0.0</span>
1201<span>N-API version: 1</span>
1202</div>
1203<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">napi_extended_error_info</span> {</span>
1204  <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* error_message;
1205  <span class="hljs-type">void</span>* engine_reserved;
1206  <span class="hljs-type">uint32_t</span> engine_error_code;
1207  napi_status error_code;
1208};</code></pre>
1209<ul>
1210<li><code>error_message</code>: Textual representation of the error that occurred.</li>
1211<li><code>engine_reserved</code>: Opaque handle reserved for engine use only.</li>
1212<li><code>engine_error_code</code>: VM specific error code.</li>
1213<li><code>error_code</code>: Node-API status code for the last error.</li>
1214</ul>
1215<p><a href="#n_api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a> returns the information for the last
1216Node-API call that was made.</p>
1217<p>Do not rely on the content or format of any of the extended information as it
1218is not subject to SemVer and may change at any time. It is intended only for
1219logging purposes.</p>
1220<h5>napi_get_last_error_info<span><a class="mark" href="#n_api_napi_get_last_error_info" id="n_api_napi_get_last_error_info">#</a></span></h5>
1221<div class="api_metadata">
1222<span>Added in: v8.0.0</span>
1223<span>N-API version: 1</span>
1224</div>
1225<pre><code class="language-c">napi_status
1226<span class="hljs-title function_">napi_get_last_error_info</span><span class="hljs-params">(napi_env env,
1227                         <span class="hljs-keyword">const</span> napi_extended_error_info** result)</span>;</code></pre>
1228<ul>
1229<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1230<li><code>[out] result</code>: The <code>napi_extended_error_info</code> structure with more
1231information about the error.</li>
1232</ul>
1233<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1234<p>This API retrieves a <code>napi_extended_error_info</code> structure with information
1235about the last error that occurred.</p>
1236<p>The content of the <code>napi_extended_error_info</code> returned is only valid up until
1237a Node-API function is called on the same <code>env</code>.</p>
1238<p>Do not rely on the content or format of any of the extended information as it
1239is not subject to SemVer and may change at any time. It is intended only for
1240logging purposes.</p>
1241<p>This API can be called even if there is a pending JavaScript exception.</p>
1242<h4>Exceptions<span><a class="mark" href="#n_api_exceptions" id="n_api_exceptions">#</a></span></h4>
1243<p>Any Node-API function call may result in a pending JavaScript exception. This is
1244the case for any of the API functions, even those that may not cause the
1245execution of JavaScript.</p>
1246<p>If the <code>napi_status</code> returned by a function is <code>napi_ok</code> then no
1247exception is pending and no additional action is required. If the
1248<code>napi_status</code> returned is anything other than <code>napi_ok</code> or
1249<code>napi_pending_exception</code>, in order to try to recover and continue
1250instead of simply returning immediately, <a href="#n_api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a>
1251must be called in order to determine if an exception is pending or not.</p>
1252<p>In many cases when a Node-API function is called and an exception is
1253already pending, the function will return immediately with a
1254<code>napi_status</code> of <code>napi_pending_exception</code>. However, this is not the case
1255for all functions. Node-API allows a subset of the functions to be
1256called to allow for some minimal cleanup before returning to JavaScript.
1257In that case, <code>napi_status</code> will reflect the status for the function. It
1258will not reflect previous pending exceptions. To avoid confusion, check
1259the error status after every function call.</p>
1260<p>When an exception is pending one of two approaches can be employed.</p>
1261<p>The first approach is to do any appropriate cleanup and then return so that
1262execution will return to JavaScript. As part of the transition back to
1263JavaScript, the exception will be thrown at the point in the JavaScript
1264code where the native method was invoked. The behavior of most Node-API calls
1265is unspecified while an exception is pending, and many will simply return
1266<code>napi_pending_exception</code>, so do as little as possible and then return to
1267JavaScript where the exception can be handled.</p>
1268<p>The second approach is to try to handle the exception. There will be cases
1269where the native code can catch the exception, take the appropriate action,
1270and then continue. This is only recommended in specific cases
1271where it is known that the exception can be safely handled. In these
1272cases <a href="#n_api_napi_get_and_clear_last_exception"><code>napi_get_and_clear_last_exception</code></a> can be used to get and
1273clear the exception. On success, result will contain the handle to
1274the last JavaScript <code>Object</code> thrown. If it is determined, after
1275retrieving the exception, the exception cannot be handled after all
1276it can be re-thrown it with <a href="#n_api_napi_throw"><code>napi_throw</code></a> where error is the
1277JavaScript value to be thrown.</p>
1278<p>The following utility functions are also available in case native code
1279needs to throw an exception or determine if a <code>napi_value</code> is an instance
1280of a JavaScript <code>Error</code> object: <a href="#n_api_napi_throw_error"><code>napi_throw_error</code></a>,
1281<a href="#n_api_napi_throw_type_error"><code>napi_throw_type_error</code></a>, <a href="#n_api_napi_throw_range_error"><code>napi_throw_range_error</code></a> and
1282<a href="#n_api_napi_is_error"><code>napi_is_error</code></a>.</p>
1283<p>The following utility functions are also available in case native
1284code needs to create an <code>Error</code> object: <a href="#n_api_napi_create_error"><code>napi_create_error</code></a>,
1285<a href="#n_api_napi_create_type_error"><code>napi_create_type_error</code></a>, and <a href="#n_api_napi_create_range_error"><code>napi_create_range_error</code></a>,
1286where result is the <code>napi_value</code> that refers to the newly created
1287JavaScript <code>Error</code> object.</p>
1288<p>The Node.js project is adding error codes to all of the errors
1289generated internally. The goal is for applications to use these
1290error codes for all error checking. The associated error messages
1291will remain, but will only be meant to be used for logging and
1292display with the expectation that the message can change without
1293SemVer applying. In order to support this model with Node-API, both
1294in internal functionality and for module specific functionality
1295(as its good practice), the <code>throw_</code> and <code>create_</code> functions
1296take an optional code parameter which is the string for the code
1297to be added to the error object. If the optional parameter is <code>NULL</code>
1298then no code will be associated with the error. If a code is provided,
1299the name associated with the error is also updated to be:</p>
1300<pre><code class="language-text">originalName [code]</code></pre>
1301<p>where <code>originalName</code> is the original name associated with the error
1302and <code>code</code> is the code that was provided. For example, if the code
1303is <code>'ERR_ERROR_1'</code> and a <code>TypeError</code> is being created the name will be:</p>
1304<pre><code class="language-text">TypeError [ERR_ERROR_1]</code></pre>
1305<h5>napi_throw<span><a class="mark" href="#n_api_napi_throw" id="n_api_napi_throw">#</a></span></h5>
1306<div class="api_metadata">
1307<span>Added in: v8.0.0</span>
1308<span>N-API version: 1</span>
1309</div>
1310<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_throw</span><span class="hljs-params">(napi_env env, napi_value error)</span>;</code></pre>
1311<ul>
1312<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1313<li><code>[in] error</code>: The JavaScript value to be thrown.</li>
1314</ul>
1315<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1316<p>This API throws the JavaScript value provided.</p>
1317<h5>napi_throw_error<span><a class="mark" href="#n_api_napi_throw_error" id="n_api_napi_throw_error">#</a></span></h5>
1318<div class="api_metadata">
1319<span>Added in: v8.0.0</span>
1320<span>N-API version: 1</span>
1321</div>
1322<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_throw_error</span><span class="hljs-params">(napi_env env,
1323                                         <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* code,
1324                                         <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* msg)</span>;</code></pre>
1325<ul>
1326<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1327<li><code>[in] code</code>: Optional error code to be set on the error.</li>
1328<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
1329</ul>
1330<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1331<p>This API throws a JavaScript <code>Error</code> with the text provided.</p>
1332<h5>napi_throw_type_error<span><a class="mark" href="#n_api_napi_throw_type_error" id="n_api_napi_throw_type_error">#</a></span></h5>
1333<div class="api_metadata">
1334<span>Added in: v8.0.0</span>
1335<span>N-API version: 1</span>
1336</div>
1337<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_throw_type_error</span><span class="hljs-params">(napi_env env,
1338                                              <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* code,
1339                                              <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* msg)</span>;</code></pre>
1340<ul>
1341<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1342<li><code>[in] code</code>: Optional error code to be set on the error.</li>
1343<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
1344</ul>
1345<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1346<p>This API throws a JavaScript <code>TypeError</code> with the text provided.</p>
1347<h5>napi_throw_range_error<span><a class="mark" href="#n_api_napi_throw_range_error" id="n_api_napi_throw_range_error">#</a></span></h5>
1348<div class="api_metadata">
1349<span>Added in: v8.0.0</span>
1350<span>N-API version: 1</span>
1351</div>
1352<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_throw_range_error</span><span class="hljs-params">(napi_env env,
1353                                               <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* code,
1354                                               <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* msg)</span>;</code></pre>
1355<ul>
1356<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1357<li><code>[in] code</code>: Optional error code to be set on the error.</li>
1358<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
1359</ul>
1360<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1361<p>This API throws a JavaScript <code>RangeError</code> with the text provided.</p>
1362<h5>napi_is_error<span><a class="mark" href="#n_api_napi_is_error" id="n_api_napi_is_error">#</a></span></h5>
1363<div class="api_metadata">
1364<span>Added in: v8.0.0</span>
1365<span>N-API version: 1</span>
1366</div>
1367<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_is_error</span><span class="hljs-params">(napi_env env,
1368                                      napi_value value,
1369                                      <span class="hljs-type">bool</span>* result)</span>;</code></pre>
1370<ul>
1371<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1372<li><code>[in] value</code>: The <code>napi_value</code> to be checked.</li>
1373<li><code>[out] result</code>: Boolean value that is set to true if <code>napi_value</code> represents
1374an error, false otherwise.</li>
1375</ul>
1376<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1377<p>This API queries a <code>napi_value</code> to check if it represents an error object.</p>
1378<h5>napi_create_error<span><a class="mark" href="#n_api_napi_create_error" id="n_api_napi_create_error">#</a></span></h5>
1379<div class="api_metadata">
1380<span>Added in: v8.0.0</span>
1381<span>N-API version: 1</span>
1382</div>
1383<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_create_error</span><span class="hljs-params">(napi_env env,
1384                                          napi_value code,
1385                                          napi_value msg,
1386                                          napi_value* result)</span>;</code></pre>
1387<ul>
1388<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1389<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
1390associated with the error.</li>
1391<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>string</code> to be used as
1392the message for the <code>Error</code>.</li>
1393<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
1394</ul>
1395<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1396<p>This API returns a JavaScript <code>Error</code> with the text provided.</p>
1397<h5>napi_create_type_error<span><a class="mark" href="#n_api_napi_create_type_error" id="n_api_napi_create_type_error">#</a></span></h5>
1398<div class="api_metadata">
1399<span>Added in: v8.0.0</span>
1400<span>N-API version: 1</span>
1401</div>
1402<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_create_type_error</span><span class="hljs-params">(napi_env env,
1403                                               napi_value code,
1404                                               napi_value msg,
1405                                               napi_value* result)</span>;</code></pre>
1406<ul>
1407<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1408<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
1409associated with the error.</li>
1410<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>string</code> to be used as
1411the message for the <code>Error</code>.</li>
1412<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
1413</ul>
1414<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1415<p>This API returns a JavaScript <code>TypeError</code> with the text provided.</p>
1416<h5>napi_create_range_error<span><a class="mark" href="#n_api_napi_create_range_error" id="n_api_napi_create_range_error">#</a></span></h5>
1417<div class="api_metadata">
1418<span>Added in: v8.0.0</span>
1419<span>N-API version: 1</span>
1420</div>
1421<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_create_range_error</span><span class="hljs-params">(napi_env env,
1422                                                napi_value code,
1423                                                napi_value msg,
1424                                                napi_value* result)</span>;</code></pre>
1425<ul>
1426<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1427<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
1428associated with the error.</li>
1429<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>string</code> to be used as
1430the message for the <code>Error</code>.</li>
1431<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
1432</ul>
1433<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1434<p>This API returns a JavaScript <code>RangeError</code> with the text provided.</p>
1435<h5>napi_get_and_clear_last_exception<span><a class="mark" href="#n_api_napi_get_and_clear_last_exception" id="n_api_napi_get_and_clear_last_exception">#</a></span></h5>
1436<div class="api_metadata">
1437<span>Added in: v8.0.0</span>
1438<span>N-API version: 1</span>
1439</div>
1440<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_and_clear_last_exception</span><span class="hljs-params">(napi_env env,
1441                                              napi_value* result)</span>;</code></pre>
1442<ul>
1443<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1444<li><code>[out] result</code>: The exception if one is pending, <code>NULL</code> otherwise.</li>
1445</ul>
1446<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1447<p>This API can be called even if there is a pending JavaScript exception.</p>
1448<h5>napi_is_exception_pending<span><a class="mark" href="#n_api_napi_is_exception_pending" id="n_api_napi_is_exception_pending">#</a></span></h5>
1449<div class="api_metadata">
1450<span>Added in: v8.0.0</span>
1451<span>N-API version: 1</span>
1452</div>
1453<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_exception_pending</span><span class="hljs-params">(napi_env env, <span class="hljs-type">bool</span>* result)</span>;</code></pre>
1454<ul>
1455<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1456<li><code>[out] result</code>: Boolean value that is set to true if an exception is pending.</li>
1457</ul>
1458<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1459<p>This API can be called even if there is a pending JavaScript exception.</p>
1460<h5>napi_fatal_exception<span><a class="mark" href="#n_api_napi_fatal_exception" id="n_api_napi_fatal_exception">#</a></span></h5>
1461<div class="api_metadata">
1462<span>Added in: v9.10.0</span>
1463<span>N-API version: 3</span>
1464</div>
1465<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_fatal_exception</span><span class="hljs-params">(napi_env env, napi_value err)</span>;</code></pre>
1466<ul>
1467<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1468<li><code>[in] err</code>: The error that is passed to <code>'uncaughtException'</code>.</li>
1469</ul>
1470<p>Trigger an <code>'uncaughtException'</code> in JavaScript. Useful if an async
1471callback throws an exception with no way to recover.</p>
1472<h4>Fatal errors<span><a class="mark" href="#n_api_fatal_errors" id="n_api_fatal_errors">#</a></span></h4>
1473<p>In the event of an unrecoverable error in a native module, a fatal error can be
1474thrown to immediately terminate the process.</p>
1475<h5>napi_fatal_error<span><a class="mark" href="#n_api_napi_fatal_error" id="n_api_napi_fatal_error">#</a></span></h5>
1476<div class="api_metadata">
1477<span>Added in: v8.2.0</span>
1478<span>N-API version: 1</span>
1479</div>
1480<pre><code class="language-c">NAPI_NO_RETURN <span class="hljs-type">void</span> <span class="hljs-title function_">napi_fatal_error</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* location,
1481                                     <span class="hljs-type">size_t</span> location_len,
1482                                     <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* message,
1483                                     <span class="hljs-type">size_t</span> message_len)</span>;</code></pre>
1484<ul>
1485<li><code>[in] location</code>: Optional location at which the error occurred.</li>
1486<li><code>[in] location_len</code>: The length of the location in bytes, or
1487<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
1488<li><code>[in] message</code>: The message associated with the error.</li>
1489<li><code>[in] message_len</code>: The length of the message in bytes, or <code>NAPI_AUTO_LENGTH</code>
1490if it is null-terminated.</li>
1491</ul>
1492<p>The function call does not return, the process will be terminated.</p>
1493<p>This API can be called even if there is a pending JavaScript exception.</p>
1494</section><section><h3>Object lifetime management<span><a class="mark" href="#n_api_object_lifetime_management" id="n_api_object_lifetime_management">#</a></span></h3>
1495<p>As Node-API calls are made, handles to objects in the heap for the underlying
1496VM may be returned as <code>napi_values</code>. These handles must hold the
1497objects 'live' until they are no longer required by the native code,
1498otherwise the objects could be collected before the native code was
1499finished using them.</p>
1500<p>As object handles are returned they are associated with a
1501'scope'. The lifespan for the default scope is tied to the lifespan
1502of the native method call. The result is that, by default, handles
1503remain valid and the objects associated with these handles will be
1504held live for the lifespan of the native method call.</p>
1505<p>In many cases, however, it is necessary that the handles remain valid for
1506either a shorter or longer lifespan than that of the native method.
1507The sections which follow describe the Node-API functions that can be used
1508to change the handle lifespan from the default.</p>
1509<h4>Making handle lifespan shorter than that of the native method<span><a class="mark" href="#n_api_making_handle_lifespan_shorter_than_that_of_the_native_method" id="n_api_making_handle_lifespan_shorter_than_that_of_the_native_method">#</a></span></h4>
1510<p>It is often necessary to make the lifespan of handles shorter than
1511the lifespan of a native method. For example, consider a native method
1512that has a loop which iterates through the elements in a large array:</p>
1513<pre><code class="language-c"><span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">1000000</span>; i++) {
1514  napi_value result;
1515  napi_status status = napi_get_element(env, object, i, &#x26;result);
1516  <span class="hljs-keyword">if</span> (status != napi_ok) {
1517    <span class="hljs-keyword">break</span>;
1518  }
1519  <span class="hljs-comment">// do something with element</span>
1520}</code></pre>
1521<p>This would result in a large number of handles being created, consuming
1522substantial resources. In addition, even though the native code could only
1523use the most recent handle, all of the associated objects would also be
1524kept alive since they all share the same scope.</p>
1525<p>To handle this case, Node-API provides the ability to establish a new 'scope' to
1526which newly created handles will be associated. Once those handles
1527are no longer required, the scope can be 'closed' and any handles associated
1528with the scope are invalidated. The methods available to open/close scopes are
1529<a href="#n_api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and <a href="#n_api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a>.</p>
1530<p>Node-API only supports a single nested hierarchy of scopes. There is only one
1531active scope at any time, and all new handles will be associated with that
1532scope while it is active. Scopes must be closed in the reverse order from
1533which they are opened. In addition, all scopes created within a native method
1534must be closed before returning from that method.</p>
1535<p>Taking the earlier example, adding calls to <a href="#n_api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and
1536<a href="#n_api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a> would ensure that at most a single handle
1537is valid throughout the execution of the loop:</p>
1538<pre><code class="language-c"><span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">1000000</span>; i++) {
1539  napi_handle_scope scope;
1540  napi_status status = napi_open_handle_scope(env, &#x26;scope);
1541  <span class="hljs-keyword">if</span> (status != napi_ok) {
1542    <span class="hljs-keyword">break</span>;
1543  }
1544  napi_value result;
1545  status = napi_get_element(env, object, i, &#x26;result);
1546  <span class="hljs-keyword">if</span> (status != napi_ok) {
1547    <span class="hljs-keyword">break</span>;
1548  }
1549  <span class="hljs-comment">// do something with element</span>
1550  status = napi_close_handle_scope(env, scope);
1551  <span class="hljs-keyword">if</span> (status != napi_ok) {
1552    <span class="hljs-keyword">break</span>;
1553  }
1554}</code></pre>
1555<p>When nesting scopes, there are cases where a handle from an
1556inner scope needs to live beyond the lifespan of that scope. Node-API supports
1557an 'escapable scope' in order to support this case. An escapable scope
1558allows one handle to be 'promoted' so that it 'escapes' the
1559current scope and the lifespan of the handle changes from the current
1560scope to that of the outer scope.</p>
1561<p>The methods available to open/close escapable scopes are
1562<a href="#n_api_napi_open_escapable_handle_scope"><code>napi_open_escapable_handle_scope</code></a> and
1563<a href="#n_api_napi_close_escapable_handle_scope"><code>napi_close_escapable_handle_scope</code></a>.</p>
1564<p>The request to promote a handle is made through <a href="#n_api_napi_escape_handle"><code>napi_escape_handle</code></a> which
1565can only be called once.</p>
1566<h5>napi_open_handle_scope<span><a class="mark" href="#n_api_napi_open_handle_scope" id="n_api_napi_open_handle_scope">#</a></span></h5>
1567<div class="api_metadata">
1568<span>Added in: v8.0.0</span>
1569<span>N-API version: 1</span>
1570</div>
1571<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_open_handle_scope</span><span class="hljs-params">(napi_env env,
1572                                               napi_handle_scope* result)</span>;</code></pre>
1573<ul>
1574<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1575<li><code>[out] result</code>: <code>napi_value</code> representing the new scope.</li>
1576</ul>
1577<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1578<p>This API opens a new scope.</p>
1579<h5>napi_close_handle_scope<span><a class="mark" href="#n_api_napi_close_handle_scope" id="n_api_napi_close_handle_scope">#</a></span></h5>
1580<div class="api_metadata">
1581<span>Added in: v8.0.0</span>
1582<span>N-API version: 1</span>
1583</div>
1584<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_close_handle_scope</span><span class="hljs-params">(napi_env env,
1585                                                napi_handle_scope scope)</span>;</code></pre>
1586<ul>
1587<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1588<li><code>[in] scope</code>: <code>napi_value</code> representing the scope to be closed.</li>
1589</ul>
1590<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1591<p>This API closes the scope passed in. Scopes must be closed in the
1592reverse order from which they were created.</p>
1593<p>This API can be called even if there is a pending JavaScript exception.</p>
1594<h5>napi_open_escapable_handle_scope<span><a class="mark" href="#n_api_napi_open_escapable_handle_scope" id="n_api_napi_open_escapable_handle_scope">#</a></span></h5>
1595<div class="api_metadata">
1596<span>Added in: v8.0.0</span>
1597<span>N-API version: 1</span>
1598</div>
1599<pre><code class="language-c">NAPI_EXTERN napi_status
1600    <span class="hljs-title function_">napi_open_escapable_handle_scope</span><span class="hljs-params">(napi_env env,
1601                                     napi_handle_scope* result)</span>;</code></pre>
1602<ul>
1603<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1604<li><code>[out] result</code>: <code>napi_value</code> representing the new scope.</li>
1605</ul>
1606<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1607<p>This API opens a new scope from which one object can be promoted
1608to the outer scope.</p>
1609<h5>napi_close_escapable_handle_scope<span><a class="mark" href="#n_api_napi_close_escapable_handle_scope" id="n_api_napi_close_escapable_handle_scope">#</a></span></h5>
1610<div class="api_metadata">
1611<span>Added in: v8.0.0</span>
1612<span>N-API version: 1</span>
1613</div>
1614<pre><code class="language-c">NAPI_EXTERN napi_status
1615    <span class="hljs-title function_">napi_close_escapable_handle_scope</span><span class="hljs-params">(napi_env env,
1616                                      napi_handle_scope scope)</span>;</code></pre>
1617<ul>
1618<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1619<li><code>[in] scope</code>: <code>napi_value</code> representing the scope to be closed.</li>
1620</ul>
1621<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1622<p>This API closes the scope passed in. Scopes must be closed in the
1623reverse order from which they were created.</p>
1624<p>This API can be called even if there is a pending JavaScript exception.</p>
1625<h5>napi_escape_handle<span><a class="mark" href="#n_api_napi_escape_handle" id="n_api_napi_escape_handle">#</a></span></h5>
1626<div class="api_metadata">
1627<span>Added in: v8.0.0</span>
1628<span>N-API version: 1</span>
1629</div>
1630<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_escape_handle</span><span class="hljs-params">(napi_env env,
1631                               napi_escapable_handle_scope scope,
1632                               napi_value escapee,
1633                               napi_value* result)</span>;</code></pre>
1634<ul>
1635<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1636<li><code>[in] scope</code>: <code>napi_value</code> representing the current scope.</li>
1637<li><code>[in] escapee</code>: <code>napi_value</code> representing the JavaScript <code>Object</code> to be
1638escaped.</li>
1639<li><code>[out] result</code>: <code>napi_value</code> representing the handle to the escaped <code>Object</code>
1640in the outer scope.</li>
1641</ul>
1642<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1643<p>This API promotes the handle to the JavaScript object so that it is valid
1644for the lifetime of the outer scope. It can only be called once per scope.
1645If it is called more than once an error will be returned.</p>
1646<p>This API can be called even if there is a pending JavaScript exception.</p>
1647<h4>References to objects with a lifespan longer than that of the native method<span><a class="mark" href="#n_api_references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method" id="n_api_references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method">#</a></span></h4>
1648<p>In some cases an addon will need to be able to create and reference objects
1649with a lifespan longer than that of a single native method invocation. For
1650example, to create a constructor and later use that constructor
1651in a request to creates instances, it must be possible to reference
1652the constructor object across many different instance creation requests. This
1653would not be possible with a normal handle returned as a <code>napi_value</code> as
1654described in the earlier section. The lifespan of a normal handle is
1655managed by scopes and all scopes must be closed before the end of a native
1656method.</p>
1657<p>Node-API provides methods to create persistent references to an object.
1658Each persistent reference has an associated count with a value of 0
1659or higher. The count determines if the reference will keep
1660the corresponding object live. References with a count of 0 do not
1661prevent the object from being collected and are often called 'weak'
1662references. Any count greater than 0 will prevent the object
1663from being collected.</p>
1664<p>References can be created with an initial reference count. The count can
1665then be modified through <a href="#n_api_napi_reference_ref"><code>napi_reference_ref</code></a> and
1666<a href="#n_api_napi_reference_unref"><code>napi_reference_unref</code></a>. If an object is collected while the count
1667for a reference is 0, all subsequent calls to
1668get the object associated with the reference <a href="#n_api_napi_get_reference_value"><code>napi_get_reference_value</code></a>
1669will return <code>NULL</code> for the returned <code>napi_value</code>. An attempt to call
1670<a href="#n_api_napi_reference_ref"><code>napi_reference_ref</code></a> for a reference whose object has been collected
1671results in an error.</p>
1672<p>References must be deleted once they are no longer required by the addon. When
1673a reference is deleted, it will no longer prevent the corresponding object from
1674being collected. Failure to delete a persistent reference results in
1675a 'memory leak' with both the native memory for the persistent reference and
1676the corresponding object on the heap being retained forever.</p>
1677<p>There can be multiple persistent references created which refer to the same
1678object, each of which will either keep the object live or not based on its
1679individual count.</p>
1680<h5>napi_create_reference<span><a class="mark" href="#n_api_napi_create_reference" id="n_api_napi_create_reference">#</a></span></h5>
1681<div class="api_metadata">
1682<span>Added in: v8.0.0</span>
1683<span>N-API version: 1</span>
1684</div>
1685<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_create_reference</span><span class="hljs-params">(napi_env env,
1686                                              napi_value value,
1687                                              <span class="hljs-type">uint32_t</span> initial_refcount,
1688                                              napi_ref* result)</span>;</code></pre>
1689<ul>
1690<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1691<li><code>[in] value</code>: <code>napi_value</code> representing the <code>Object</code> to which we want a
1692reference.</li>
1693<li><code>[in] initial_refcount</code>: Initial reference count for the new reference.</li>
1694<li><code>[out] result</code>: <code>napi_ref</code> pointing to the new reference.</li>
1695</ul>
1696<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1697<p>This API create a new reference with the specified reference count
1698to the <code>Object</code> passed in.</p>
1699<h5>napi_delete_reference<span><a class="mark" href="#n_api_napi_delete_reference" id="n_api_napi_delete_reference">#</a></span></h5>
1700<div class="api_metadata">
1701<span>Added in: v8.0.0</span>
1702<span>N-API version: 1</span>
1703</div>
1704<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_delete_reference</span><span class="hljs-params">(napi_env env, napi_ref ref)</span>;</code></pre>
1705<ul>
1706<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1707<li><code>[in] ref</code>: <code>napi_ref</code> to be deleted.</li>
1708</ul>
1709<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1710<p>This API deletes the reference passed in.</p>
1711<p>This API can be called even if there is a pending JavaScript exception.</p>
1712<h5>napi_reference_ref<span><a class="mark" href="#n_api_napi_reference_ref" id="n_api_napi_reference_ref">#</a></span></h5>
1713<div class="api_metadata">
1714<span>Added in: v8.0.0</span>
1715<span>N-API version: 1</span>
1716</div>
1717<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_reference_ref</span><span class="hljs-params">(napi_env env,
1718                                           napi_ref ref,
1719                                           <span class="hljs-type">uint32_t</span>* result)</span>;</code></pre>
1720<ul>
1721<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1722<li><code>[in] ref</code>: <code>napi_ref</code> for which the reference count will be incremented.</li>
1723<li><code>[out] result</code>: The new reference count.</li>
1724</ul>
1725<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1726<p>This API increments the reference count for the reference
1727passed in and returns the resulting reference count.</p>
1728<h5>napi_reference_unref<span><a class="mark" href="#n_api_napi_reference_unref" id="n_api_napi_reference_unref">#</a></span></h5>
1729<div class="api_metadata">
1730<span>Added in: v8.0.0</span>
1731<span>N-API version: 1</span>
1732</div>
1733<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_reference_unref</span><span class="hljs-params">(napi_env env,
1734                                             napi_ref ref,
1735                                             <span class="hljs-type">uint32_t</span>* result)</span>;</code></pre>
1736<ul>
1737<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1738<li><code>[in] ref</code>: <code>napi_ref</code> for which the reference count will be decremented.</li>
1739<li><code>[out] result</code>: The new reference count.</li>
1740</ul>
1741<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1742<p>This API decrements the reference count for the reference
1743passed in and returns the resulting reference count.</p>
1744<h5>napi_get_reference_value<span><a class="mark" href="#n_api_napi_get_reference_value" id="n_api_napi_get_reference_value">#</a></span></h5>
1745<div class="api_metadata">
1746<span>Added in: v8.0.0</span>
1747<span>N-API version: 1</span>
1748</div>
1749<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_get_reference_value</span><span class="hljs-params">(napi_env env,
1750                                                 napi_ref ref,
1751                                                 napi_value* result)</span>;</code></pre>
1752<p>the <code>napi_value passed</code> in or out of these methods is a handle to the
1753object to which the reference is related.</p>
1754<ul>
1755<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1756<li><code>[in] ref</code>: <code>napi_ref</code> for which we requesting the corresponding <code>Object</code>.</li>
1757<li><code>[out] result</code>: The <code>napi_value</code> for the <code>Object</code> referenced by the
1758<code>napi_ref</code>.</li>
1759</ul>
1760<p>Returns <code>napi_ok</code> if the API succeeded.</p>
1761<p>If still valid, this API returns the <code>napi_value</code> representing the
1762JavaScript <code>Object</code> associated with the <code>napi_ref</code>. Otherwise, result
1763will be <code>NULL</code>.</p>
1764<h4>Cleanup on exit of the current Node.js instance<span><a class="mark" href="#n_api_cleanup_on_exit_of_the_current_node_js_instance" id="n_api_cleanup_on_exit_of_the_current_node_js_instance">#</a></span></h4>
1765<p>While a Node.js process typically releases all its resources when exiting,
1766embedders of Node.js, or future Worker support, may require addons to register
1767clean-up hooks that will be run once the current Node.js instance exits.</p>
1768<p>Node-API provides functions for registering and un-registering such callbacks.
1769When those callbacks are run, all resources that are being held by the addon
1770should be freed up.</p>
1771<h5>napi_add_env_cleanup_hook<span><a class="mark" href="#n_api_napi_add_env_cleanup_hook" id="n_api_napi_add_env_cleanup_hook">#</a></span></h5>
1772<div class="api_metadata">
1773<span>Added in: v10.2.0</span>
1774<span>N-API version: 3</span>
1775</div>
1776<pre><code class="language-c">NODE_EXTERN napi_status <span class="hljs-title function_">napi_add_env_cleanup_hook</span><span class="hljs-params">(napi_env env,
1777                                                  <span class="hljs-type">void</span> (*fun)(<span class="hljs-type">void</span>* arg),
1778                                                  <span class="hljs-type">void</span>* arg)</span>;</code></pre>
1779<p>Registers <code>fun</code> as a function to be run with the <code>arg</code> parameter once the
1780current Node.js environment exits.</p>
1781<p>A function can safely be specified multiple times with different
1782<code>arg</code> values. In that case, it will be called multiple times as well.
1783Providing the same <code>fun</code> and <code>arg</code> values multiple times is not allowed
1784and will lead the process to abort.</p>
1785<p>The hooks will be called in reverse order, i.e. the most recently added one
1786will be called first.</p>
1787<p>Removing this hook can be done by using <a href="#n_api_napi_remove_env_cleanup_hook"><code>napi_remove_env_cleanup_hook</code></a>.
1788Typically, that happens when the resource for which this hook was added
1789is being torn down anyway.</p>
1790<p>For asynchronous cleanup, <a href="#n_api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a> is available.</p>
1791<h5>napi_remove_env_cleanup_hook<span><a class="mark" href="#n_api_napi_remove_env_cleanup_hook" id="n_api_napi_remove_env_cleanup_hook">#</a></span></h5>
1792<div class="api_metadata">
1793<span>Added in: v10.2.0</span>
1794<span>N-API version: 3</span>
1795</div>
1796<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_remove_env_cleanup_hook</span><span class="hljs-params">(napi_env env,
1797                                                     <span class="hljs-type">void</span> (*fun)(<span class="hljs-type">void</span>* arg),
1798                                                     <span class="hljs-type">void</span>* arg)</span>;</code></pre>
1799<p>Unregisters <code>fun</code> as a function to be run with the <code>arg</code> parameter once the
1800current Node.js environment exits. Both the argument and the function value
1801need to be exact matches.</p>
1802<p>The function must have originally been registered
1803with <code>napi_add_env_cleanup_hook</code>, otherwise the process will abort.</p>
1804<h5>napi_add_async_cleanup_hook<span><a class="mark" href="#n_api_napi_add_async_cleanup_hook" id="n_api_napi_add_async_cleanup_hook">#</a></span></h5>
1805<div class="api_metadata">
1806<details class="changelog"><summary>History</summary>
1807<table>
1808<tbody><tr><th>Version</th><th>Changes</th></tr>
1809<tr><td>v14.10.0</td>
1810<td><p>Changed signature of the <code>hook</code> callback.</p></td></tr>
1811<tr><td>v14.8.0, v12.19.0</td>
1812<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
1813</tbody></table>
1814</details>
1815<span>N-API version: 8</span>
1816</div>
1817<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_add_async_cleanup_hook</span><span class="hljs-params">(
1818    napi_env env,
1819    napi_async_cleanup_hook hook,
1820    <span class="hljs-type">void</span>* arg,
1821    napi_async_cleanup_hook_handle* remove_handle)</span>;</code></pre>
1822<ul>
1823<li><code>[in] env</code>: The environment that the API is invoked under.</li>
1824<li><code>[in] hook</code>: The function pointer to call at environment teardown.</li>
1825<li><code>[in] arg</code>: The pointer to pass to <code>hook</code> when it gets called.</li>
1826<li><code>[out] remove_handle</code>: Optional handle that refers to the asynchronous cleanup
1827hook.</li>
1828</ul>
1829<p>Registers <code>hook</code>, which is a function of type <a href="#n_api_napi_async_cleanup_hook"><code>napi_async_cleanup_hook</code></a>, as
1830a function to be run with the <code>remove_handle</code> and <code>arg</code> parameters once the
1831current Node.js environment exits.</p>
1832<p>Unlike <a href="#n_api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>, the hook is allowed to be asynchronous.</p>
1833<p>Otherwise, behavior generally matches that of <a href="#n_api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>.</p>
1834<p>If <code>remove_handle</code> is not <code>NULL</code>, an opaque value will be stored in it
1835that must later be passed to <a href="#n_api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a>,
1836regardless of whether the hook has already been invoked.
1837Typically, that happens when the resource for which this hook was added
1838is being torn down anyway.</p>
1839<h5>napi_remove_async_cleanup_hook<span><a class="mark" href="#n_api_napi_remove_async_cleanup_hook" id="n_api_napi_remove_async_cleanup_hook">#</a></span></h5>
1840<div class="api_metadata">
1841<details class="changelog"><summary>History</summary>
1842<table>
1843<tbody><tr><th>Version</th><th>Changes</th></tr>
1844<tr><td>v14.10.0</td>
1845<td><p>Removed <code>env</code> parameter.</p></td></tr>
1846<tr><td>v14.8.0</td>
1847<td><p><span>Added in: v14.8.0</span></p></td></tr>
1848</tbody></table>
1849</details>
1850</div>
1851<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_remove_async_cleanup_hook</span><span class="hljs-params">(
1852    napi_async_cleanup_hook_handle remove_handle)</span>;</code></pre>
1853<ul>
1854<li><code>[in] remove_handle</code>: The handle to an asynchronous cleanup hook that was
1855created with <a href="#n_api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>.</li>
1856</ul>
1857<p>Unregisters the cleanup hook corresponding to <code>remove_handle</code>. This will prevent
1858the hook from being executed, unless it has already started executing.
1859This must be called on any <code>napi_async_cleanup_hook_handle</code> value obtained
1860from <a href="#n_api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>.</p>
1861</section><section><h3>Module registration<span><a class="mark" href="#n_api_module_registration" id="n_api_module_registration">#</a></span></h3>
1862<p>Node-API modules are registered in a manner similar to other modules
1863except that instead of using the <code>NODE_MODULE</code> macro the following
1864is used:</p>
1865<pre><code class="language-c">NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)</code></pre>
1866<p>The next difference is the signature for the <code>Init</code> method. For a Node-API
1867module it is as follows:</p>
1868<pre><code class="language-c">napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span>;</code></pre>
1869<p>The return value from <code>Init</code> is treated as the <code>exports</code> object for the module.
1870The <code>Init</code> method is passed an empty object via the <code>exports</code> parameter as a
1871convenience. If <code>Init</code> returns <code>NULL</code>, the parameter passed as <code>exports</code> is
1872exported by the module. Node-API modules cannot modify the <code>module</code> object but
1873can specify anything as the <code>exports</code> property of the module.</p>
1874<p>To add the method <code>hello</code> as a function so that it can be called as a method
1875provided by the addon:</p>
1876<pre><code class="language-c">napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
1877  napi_status status;
1878  napi_property_descriptor desc = {
1879    <span class="hljs-string">"hello"</span>,
1880    <span class="hljs-literal">NULL</span>,
1881    Method,
1882    <span class="hljs-literal">NULL</span>,
1883    <span class="hljs-literal">NULL</span>,
1884    <span class="hljs-literal">NULL</span>,
1885    napi_writable | napi_enumerable | napi_configurable,
1886    <span class="hljs-literal">NULL</span>
1887  };
1888  status = napi_define_properties(env, exports, <span class="hljs-number">1</span>, &#x26;desc);
1889  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
1890  <span class="hljs-keyword">return</span> exports;
1891}</code></pre>
1892<p>To set a function to be returned by the <code>require()</code> for the addon:</p>
1893<pre><code class="language-c">napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
1894  napi_value method;
1895  napi_status status;
1896  status = napi_create_function(env, <span class="hljs-string">"exports"</span>, NAPI_AUTO_LENGTH, Method, <span class="hljs-literal">NULL</span>, &#x26;method);
1897  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
1898  <span class="hljs-keyword">return</span> method;
1899}</code></pre>
1900<p>To define a class so that new instances can be created (often used with
1901<a href="#n_api_object_wrap">Object wrap</a>):</p>
1902<pre><code class="language-c"><span class="hljs-comment">// <span class="hljs-doctag">NOTE:</span> partial example, not all referenced code is included</span>
1903napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
1904  napi_status status;
1905  napi_property_descriptor properties[] = {
1906    { <span class="hljs-string">"value"</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, GetValue, SetValue, <span class="hljs-literal">NULL</span>, napi_writable | napi_configurable, <span class="hljs-literal">NULL</span> },
1907    DECLARE_NAPI_METHOD(<span class="hljs-string">"plusOne"</span>, PlusOne),
1908    DECLARE_NAPI_METHOD(<span class="hljs-string">"multiply"</span>, Multiply),
1909  };
1910
1911  napi_value cons;
1912  status =
1913      napi_define_class(env, <span class="hljs-string">"MyObject"</span>, New, <span class="hljs-literal">NULL</span>, <span class="hljs-number">3</span>, properties, &#x26;cons);
1914  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
1915
1916  status = napi_create_reference(env, cons, <span class="hljs-number">1</span>, &#x26;constructor);
1917  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
1918
1919  status = napi_set_named_property(env, exports, <span class="hljs-string">"MyObject"</span>, cons);
1920  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
1921
1922  <span class="hljs-keyword">return</span> exports;
1923}</code></pre>
1924<p>You can also use the <code>NAPI_MODULE_INIT</code> macro, which acts as a shorthand
1925for <code>NAPI_MODULE</code> and defining an <code>Init</code> function:</p>
1926<pre><code class="language-c">NAPI_MODULE_INIT() {
1927  napi_value answer;
1928  napi_status result;
1929
1930  status = napi_create_int64(env, <span class="hljs-number">42</span>, &#x26;answer);
1931  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
1932
1933  status = napi_set_named_property(env, exports, <span class="hljs-string">"answer"</span>, answer);
1934  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
1935
1936  <span class="hljs-keyword">return</span> exports;
1937}</code></pre>
1938<p>All Node-API addons are context-aware, meaning they may be loaded multiple
1939times. There are a few design considerations when declaring such a module.
1940The documentation on <a href="addons.html#addons_context_aware_addons">context-aware addons</a> provides more details.</p>
1941<p>The variables <code>env</code> and <code>exports</code> will be available inside the function body
1942following the macro invocation.</p>
1943<p>For more details on setting properties on objects, see the section on
1944<a href="#n_api_working_with_javascript_properties">Working with JavaScript properties</a>.</p>
1945<p>For more details on building addon modules in general, refer to the existing
1946API.</p>
1947</section><section><h3>Working with JavaScript values<span><a class="mark" href="#n_api_working_with_javascript_values" id="n_api_working_with_javascript_values">#</a></span></h3>
1948<p>Node-API exposes a set of APIs to create all types of JavaScript values.
1949Some of these types are documented under <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Section 6</a>
1950of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
1951<p>Fundamentally, these APIs are used to do one of the following:</p>
1952<ol>
1953<li>Create a new JavaScript object</li>
1954<li>Convert from a primitive C type to a Node-API value</li>
1955<li>Convert from Node-API value to a primitive C type</li>
1956<li>Get global instances including <code>undefined</code> and <code>null</code></li>
1957</ol>
1958<p>Node-API values are represented by the type <code>napi_value</code>.
1959Any Node-API call that requires a JavaScript value takes in a <code>napi_value</code>.
1960In some cases, the API does check the type of the <code>napi_value</code> up-front.
1961However, for better performance, it's better for the caller to make sure that
1962the <code>napi_value</code> in question is of the JavaScript type expected by the API.</p>
1963<h4>Enum types<span><a class="mark" href="#n_api_enum_types" id="n_api_enum_types">#</a></span></h4>
1964<h5>napi_key_collection_mode<span><a class="mark" href="#n_api_napi_key_collection_mode" id="n_api_napi_key_collection_mode">#</a></span></h5>
1965<div class="api_metadata">
1966<span>Added in: v13.7.0, v10.20.0</span>
1967<span>N-API version: 6</span>
1968</div>
1969<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
1970  napi_key_include_prototypes,
1971  napi_key_own_only
1972} napi_key_collection_mode;</code></pre>
1973<p>Describes the <code>Keys/Properties</code> filter enums:</p>
1974<p><code>napi_key_collection_mode</code> limits the range of collected properties.</p>
1975<p><code>napi_key_own_only</code> limits the collected properties to the given
1976object only. <code>napi_key_include_prototypes</code> will include all keys
1977of the objects's prototype chain as well.</p>
1978<h5>napi_key_filter<span><a class="mark" href="#n_api_napi_key_filter" id="n_api_napi_key_filter">#</a></span></h5>
1979<div class="api_metadata">
1980<span>Added in: v13.7.0, v10.20.0</span>
1981<span>N-API version: 6</span>
1982</div>
1983<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
1984  napi_key_all_properties = <span class="hljs-number">0</span>,
1985  napi_key_writable = <span class="hljs-number">1</span>,
1986  napi_key_enumerable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">1</span>,
1987  napi_key_configurable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">2</span>,
1988  napi_key_skip_strings = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">3</span>,
1989  napi_key_skip_symbols = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">4</span>
1990} napi_key_filter;</code></pre>
1991<p>Property filter bits. They can be or'ed to build a composite filter.</p>
1992<h5>napi_key_conversion<span><a class="mark" href="#n_api_napi_key_conversion" id="n_api_napi_key_conversion">#</a></span></h5>
1993<div class="api_metadata">
1994<span>Added in: v13.7.0, v10.20.0</span>
1995<span>N-API version: 6</span>
1996</div>
1997<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
1998  napi_key_keep_numbers,
1999  napi_key_numbers_to_strings
2000} napi_key_conversion;</code></pre>
2001<p><code>napi_key_numbers_to_strings</code> will convert integer indices to
2002strings. <code>napi_key_keep_numbers</code> will return numbers for integer
2003indices.</p>
2004<h5>napi_valuetype<span><a class="mark" href="#n_api_napi_valuetype" id="n_api_napi_valuetype">#</a></span></h5>
2005<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
2006  <span class="hljs-comment">// ES6 types (corresponds to typeof)</span>
2007  napi_undefined,
2008  napi_null,
2009  napi_boolean,
2010  napi_number,
2011  napi_string,
2012  napi_symbol,
2013  napi_object,
2014  napi_function,
2015  napi_external,
2016  napi_bigint,
2017} napi_valuetype;</code></pre>
2018<p>Describes the type of a <code>napi_value</code>. This generally corresponds to the types
2019described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types">Section 6.1</a> of the ECMAScript Language Specification.
2020In addition to types in that section, <code>napi_valuetype</code> can also represent
2021<code>Function</code>s and <code>Object</code>s with external data.</p>
2022<p>A JavaScript value of type <code>napi_external</code> appears in JavaScript as a plain
2023object such that no properties can be set on it, and no prototype.</p>
2024<h5>napi_typedarray_type<span><a class="mark" href="#n_api_napi_typedarray_type" id="n_api_napi_typedarray_type">#</a></span></h5>
2025<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
2026  napi_int8_array,
2027  napi_uint8_array,
2028  napi_uint8_clamped_array,
2029  napi_int16_array,
2030  napi_uint16_array,
2031  napi_int32_array,
2032  napi_uint32_array,
2033  napi_float32_array,
2034  napi_float64_array,
2035  napi_bigint64_array,
2036  napi_biguint64_array,
2037} napi_typedarray_type;</code></pre>
2038<p>This represents the underlying binary scalar datatype of the <code>TypedArray</code>.
2039Elements of this enum correspond to
2040<a href="https://tc39.github.io/ecma262/#sec-typedarray-objects">Section 22.2</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
2041<h4>Object creation functions<span><a class="mark" href="#n_api_object_creation_functions" id="n_api_object_creation_functions">#</a></span></h4>
2042<h5>napi_create_array<span><a class="mark" href="#n_api_napi_create_array" id="n_api_napi_create_array">#</a></span></h5>
2043<div class="api_metadata">
2044<span>Added in: v8.0.0</span>
2045<span>N-API version: 1</span>
2046</div>
2047<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_array</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code></pre>
2048<ul>
2049<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
2050<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Array</code>.</li>
2051</ul>
2052<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2053<p>This API returns a Node-API value corresponding to a JavaScript <code>Array</code> type.
2054JavaScript arrays are described in
2055<a href="https://tc39.github.io/ecma262/#sec-array-objects">Section 22.1</a> of the ECMAScript Language Specification.</p>
2056<h5>napi_create_array_with_length<span><a class="mark" href="#n_api_napi_create_array_with_length" id="n_api_napi_create_array_with_length">#</a></span></h5>
2057<div class="api_metadata">
2058<span>Added in: v8.0.0</span>
2059<span>N-API version: 1</span>
2060</div>
2061<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_array_with_length</span><span class="hljs-params">(napi_env env,
2062                                          <span class="hljs-type">size_t</span> length,
2063                                          napi_value* result)</span></code></pre>
2064<ul>
2065<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2066<li><code>[in] length</code>: The initial length of the <code>Array</code>.</li>
2067<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Array</code>.</li>
2068</ul>
2069<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2070<p>This API returns a Node-API value corresponding to a JavaScript <code>Array</code> type.
2071The <code>Array</code>'s length property is set to the passed-in length parameter.
2072However, the underlying buffer is not guaranteed to be pre-allocated by the VM
2073when the array is created. That behavior is left to the underlying VM
2074implementation. If the buffer must be a contiguous block of memory that can be
2075directly read and/or written via C, consider using
2076<a href="#n_api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a>.</p>
2077<p>JavaScript arrays are described in
2078<a href="https://tc39.github.io/ecma262/#sec-array-objects">Section 22.1</a> of the ECMAScript Language Specification.</p>
2079<h5>napi_create_arraybuffer<span><a class="mark" href="#n_api_napi_create_arraybuffer" id="n_api_napi_create_arraybuffer">#</a></span></h5>
2080<div class="api_metadata">
2081<span>Added in: v8.0.0</span>
2082<span>N-API version: 1</span>
2083</div>
2084<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_arraybuffer</span><span class="hljs-params">(napi_env env,
2085                                    <span class="hljs-type">size_t</span> byte_length,
2086                                    <span class="hljs-type">void</span>** data,
2087                                    napi_value* result)</span></code></pre>
2088<ul>
2089<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2090<li><code>[in] length</code>: The length in bytes of the array buffer to create.</li>
2091<li><code>[out] data</code>: Pointer to the underlying byte buffer of the <code>ArrayBuffer</code>.</li>
2092<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>ArrayBuffer</code>.</li>
2093</ul>
2094<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2095<p>This API returns a Node-API value corresponding to a JavaScript <code>ArrayBuffer</code>.
2096<code>ArrayBuffer</code>s are used to represent fixed-length binary data buffers. They are
2097normally used as a backing-buffer for <code>TypedArray</code> objects.
2098The <code>ArrayBuffer</code> allocated will have an underlying byte buffer whose size is
2099determined by the <code>length</code> parameter that's passed in.
2100The underlying buffer is optionally returned back to the caller in case the
2101caller wants to directly manipulate the buffer. This buffer can only be
2102written to directly from native code. To write to this buffer from JavaScript,
2103a typed array or <code>DataView</code> object would need to be created.</p>
2104<p>JavaScript <code>ArrayBuffer</code> objects are described in
2105<a href="https://tc39.github.io/ecma262/#sec-arraybuffer-objects">Section 24.1</a> of the ECMAScript Language Specification.</p>
2106<h5>napi_create_buffer<span><a class="mark" href="#n_api_napi_create_buffer" id="n_api_napi_create_buffer">#</a></span></h5>
2107<div class="api_metadata">
2108<span>Added in: v8.0.0</span>
2109<span>N-API version: 1</span>
2110</div>
2111<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_buffer</span><span class="hljs-params">(napi_env env,
2112                               <span class="hljs-type">size_t</span> size,
2113                               <span class="hljs-type">void</span>** data,
2114                               napi_value* result)</span></code></pre>
2115<ul>
2116<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2117<li><code>[in] size</code>: Size in bytes of the underlying buffer.</li>
2118<li><code>[out] data</code>: Raw pointer to the underlying buffer.</li>
2119<li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li>
2120</ul>
2121<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2122<p>This API allocates a <code>node::Buffer</code> object. While this is still a
2123fully-supported data structure, in most cases using a <code>TypedArray</code> will suffice.</p>
2124<h5>napi_create_buffer_copy<span><a class="mark" href="#n_api_napi_create_buffer_copy" id="n_api_napi_create_buffer_copy">#</a></span></h5>
2125<div class="api_metadata">
2126<span>Added in: v8.0.0</span>
2127<span>N-API version: 1</span>
2128</div>
2129<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_buffer_copy</span><span class="hljs-params">(napi_env env,
2130                                    <span class="hljs-type">size_t</span> length,
2131                                    <span class="hljs-keyword">const</span> <span class="hljs-type">void</span>* data,
2132                                    <span class="hljs-type">void</span>** result_data,
2133                                    napi_value* result)</span></code></pre>
2134<ul>
2135<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2136<li><code>[in] size</code>: Size in bytes of the input buffer (should be the same as the size
2137of the new buffer).</li>
2138<li><code>[in] data</code>: Raw pointer to the underlying buffer to copy from.</li>
2139<li><code>[out] result_data</code>: Pointer to the new <code>Buffer</code>'s underlying data buffer.</li>
2140<li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li>
2141</ul>
2142<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2143<p>This API allocates a <code>node::Buffer</code> object and initializes it with data copied
2144from the passed-in buffer. While this is still a fully-supported data
2145structure, in most cases using a <code>TypedArray</code> will suffice.</p>
2146<h5>napi_create_date<span><a class="mark" href="#n_api_napi_create_date" id="n_api_napi_create_date">#</a></span></h5>
2147<div class="api_metadata">
2148<span>Added in: v11.11.0, v10.17.0</span>
2149<span>N-API version: 5</span>
2150</div>
2151<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_date</span><span class="hljs-params">(napi_env env,
2152                             <span class="hljs-type">double</span> time,
2153                             napi_value* result)</span>;</code></pre>
2154<ul>
2155<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2156<li><code>[in] time</code>: ECMAScript time value in milliseconds since 01 January, 1970 UTC.</li>
2157<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Date</code>.</li>
2158</ul>
2159<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2160<p>This API does not observe leap seconds; they are ignored, as
2161ECMAScript aligns with POSIX time specification.</p>
2162<p>This API allocates a JavaScript <code>Date</code> object.</p>
2163<p>JavaScript <code>Date</code> objects are described in
2164<a href="https://tc39.github.io/ecma262/#sec-date-objects">Section 20.3</a> of the ECMAScript Language Specification.</p>
2165<h5>napi_create_external<span><a class="mark" href="#n_api_napi_create_external" id="n_api_napi_create_external">#</a></span></h5>
2166<div class="api_metadata">
2167<span>Added in: v8.0.0</span>
2168<span>N-API version: 1</span>
2169</div>
2170<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_external</span><span class="hljs-params">(napi_env env,
2171                                 <span class="hljs-type">void</span>* data,
2172                                 napi_finalize finalize_cb,
2173                                 <span class="hljs-type">void</span>* finalize_hint,
2174                                 napi_value* result)</span></code></pre>
2175<ul>
2176<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2177<li><code>[in] data</code>: Raw pointer to the external data.</li>
2178<li><code>[in] finalize_cb</code>: Optional callback to call when the external value is being
2179collected. <a href="#n_api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
2180<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
2181collection.</li>
2182<li><code>[out] result</code>: A <code>napi_value</code> representing an external value.</li>
2183</ul>
2184<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2185<p>This API allocates a JavaScript value with external data attached to it. This
2186is used to pass external data through JavaScript code, so it can be retrieved
2187later by native code using <a href="#n_api_napi_get_value_external"><code>napi_get_value_external</code></a>.</p>
2188<p>The API adds a <code>napi_finalize</code> callback which will be called when the JavaScript
2189object just created is ready for garbage collection. It is similar to
2190<code>napi_wrap()</code> except that:</p>
2191<ul>
2192<li>the native data cannot be retrieved later using <code>napi_unwrap()</code>,</li>
2193<li>nor can it be removed later using <code>napi_remove_wrap()</code>, and</li>
2194<li>the object created by the API can be used with <code>napi_wrap()</code>.</li>
2195</ul>
2196<p>The created value is not an object, and therefore does not support additional
2197properties. It is considered a distinct value type: calling <code>napi_typeof()</code> with
2198an external value yields <code>napi_external</code>.</p>
2199<h5>napi_create_external_arraybuffer<span><a class="mark" href="#n_api_napi_create_external_arraybuffer" id="n_api_napi_create_external_arraybuffer">#</a></span></h5>
2200<div class="api_metadata">
2201<span>Added in: v8.0.0</span>
2202<span>N-API version: 1</span>
2203</div>
2204<pre><code class="language-c">napi_status
2205<span class="hljs-title function_">napi_create_external_arraybuffer</span><span class="hljs-params">(napi_env env,
2206                                 <span class="hljs-type">void</span>* external_data,
2207                                 <span class="hljs-type">size_t</span> byte_length,
2208                                 napi_finalize finalize_cb,
2209                                 <span class="hljs-type">void</span>* finalize_hint,
2210                                 napi_value* result)</span></code></pre>
2211<ul>
2212<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2213<li><code>[in] external_data</code>: Pointer to the underlying byte buffer of the
2214<code>ArrayBuffer</code>.</li>
2215<li><code>[in] byte_length</code>: The length in bytes of the underlying buffer.</li>
2216<li><code>[in] finalize_cb</code>: Optional callback to call when the <code>ArrayBuffer</code> is being
2217collected. <a href="#n_api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
2218<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
2219collection.</li>
2220<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>ArrayBuffer</code>.</li>
2221</ul>
2222<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2223<p>This API returns a Node-API value corresponding to a JavaScript <code>ArrayBuffer</code>.
2224The underlying byte buffer of the <code>ArrayBuffer</code> is externally allocated and
2225managed. The caller must ensure that the byte buffer remains valid until the
2226finalize callback is called.</p>
2227<p>The API adds a <code>napi_finalize</code> callback which will be called when the JavaScript
2228object just created is ready for garbage collection. It is similar to
2229<code>napi_wrap()</code> except that:</p>
2230<ul>
2231<li>the native data cannot be retrieved later using <code>napi_unwrap()</code>,</li>
2232<li>nor can it be removed later using <code>napi_remove_wrap()</code>, and</li>
2233<li>the object created by the API can be used with <code>napi_wrap()</code>.</li>
2234</ul>
2235<p>JavaScript <code>ArrayBuffer</code>s are described in
2236<a href="https://tc39.github.io/ecma262/#sec-arraybuffer-objects">Section 24.1</a> of the ECMAScript Language Specification.</p>
2237<h5>napi_create_external_buffer<span><a class="mark" href="#n_api_napi_create_external_buffer" id="n_api_napi_create_external_buffer">#</a></span></h5>
2238<div class="api_metadata">
2239<span>Added in: v8.0.0</span>
2240<span>N-API version: 1</span>
2241</div>
2242<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_external_buffer</span><span class="hljs-params">(napi_env env,
2243                                        <span class="hljs-type">size_t</span> length,
2244                                        <span class="hljs-type">void</span>* data,
2245                                        napi_finalize finalize_cb,
2246                                        <span class="hljs-type">void</span>* finalize_hint,
2247                                        napi_value* result)</span></code></pre>
2248<ul>
2249<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2250<li><code>[in] length</code>: Size in bytes of the input buffer (should be the same as the
2251size of the new buffer).</li>
2252<li><code>[in] data</code>: Raw pointer to the underlying buffer to expose to JavaScript.</li>
2253<li><code>[in] finalize_cb</code>: Optional callback to call when the <code>ArrayBuffer</code> is being
2254collected. <a href="#n_api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
2255<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
2256collection.</li>
2257<li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li>
2258</ul>
2259<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2260<p>This API allocates a <code>node::Buffer</code> object and initializes it with data
2261backed by the passed in buffer. While this is still a fully-supported data
2262structure, in most cases using a <code>TypedArray</code> will suffice.</p>
2263<p>The API adds a <code>napi_finalize</code> callback which will be called when the JavaScript
2264object just created is ready for garbage collection. It is similar to
2265<code>napi_wrap()</code> except that:</p>
2266<ul>
2267<li>the native data cannot be retrieved later using <code>napi_unwrap()</code>,</li>
2268<li>nor can it be removed later using <code>napi_remove_wrap()</code>, and</li>
2269<li>the object created by the API can be used with <code>napi_wrap()</code>.</li>
2270</ul>
2271<p>For Node.js >=4 <code>Buffers</code> are <code>Uint8Array</code>s.</p>
2272<h5>napi_create_object<span><a class="mark" href="#n_api_napi_create_object" id="n_api_napi_create_object">#</a></span></h5>
2273<div class="api_metadata">
2274<span>Added in: v8.0.0</span>
2275<span>N-API version: 1</span>
2276</div>
2277<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_object</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code></pre>
2278<ul>
2279<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2280<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Object</code>.</li>
2281</ul>
2282<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2283<p>This API allocates a default JavaScript <code>Object</code>.
2284It is the equivalent of doing <code>new Object()</code> in JavaScript.</p>
2285<p>The JavaScript <code>Object</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-object-type">Section 6.1.7</a> of the
2286ECMAScript Language Specification.</p>
2287<h5>napi_create_symbol<span><a class="mark" href="#n_api_napi_create_symbol" id="n_api_napi_create_symbol">#</a></span></h5>
2288<div class="api_metadata">
2289<span>Added in: v8.0.0</span>
2290<span>N-API version: 1</span>
2291</div>
2292<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_symbol</span><span class="hljs-params">(napi_env env,
2293                               napi_value description,
2294                               napi_value* result)</span></code></pre>
2295<ul>
2296<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2297<li><code>[in] description</code>: Optional <code>napi_value</code> which refers to a JavaScript
2298<code>string</code> to be set as the description for the symbol.</li>
2299<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>symbol</code>.</li>
2300</ul>
2301<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2302<p>This API creates a JavaScript <code>symbol</code> value from a UTF8-encoded C string.</p>
2303<p>The JavaScript <code>symbol</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-symbol-objects">Section 19.4</a>
2304of the ECMAScript Language Specification.</p>
2305<h5>napi_create_typedarray<span><a class="mark" href="#n_api_napi_create_typedarray" id="n_api_napi_create_typedarray">#</a></span></h5>
2306<div class="api_metadata">
2307<span>Added in: v8.0.0</span>
2308<span>N-API version: 1</span>
2309</div>
2310<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_typedarray</span><span class="hljs-params">(napi_env env,
2311                                   napi_typedarray_type type,
2312                                   <span class="hljs-type">size_t</span> length,
2313                                   napi_value arraybuffer,
2314                                   <span class="hljs-type">size_t</span> byte_offset,
2315                                   napi_value* result)</span></code></pre>
2316<ul>
2317<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2318<li><code>[in] type</code>: Scalar datatype of the elements within the <code>TypedArray</code>.</li>
2319<li><code>[in] length</code>: Number of elements in the <code>TypedArray</code>.</li>
2320<li><code>[in] arraybuffer</code>: <code>ArrayBuffer</code> underlying the typed array.</li>
2321<li><code>[in] byte_offset</code>: The byte offset within the <code>ArrayBuffer</code> from which to
2322start projecting the <code>TypedArray</code>.</li>
2323<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>TypedArray</code>.</li>
2324</ul>
2325<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2326<p>This API creates a JavaScript <code>TypedArray</code> object over an existing
2327<code>ArrayBuffer</code>. <code>TypedArray</code> objects provide an array-like view over an
2328underlying data buffer where each element has the same underlying binary scalar
2329datatype.</p>
2330<p>It's required that <code>(length * size_of_element) + byte_offset</code> should
2331be &#x3C;= the size in bytes of the array passed in. If not, a <code>RangeError</code> exception
2332is raised.</p>
2333<p>JavaScript <code>TypedArray</code> objects are described in
2334<a href="https://tc39.github.io/ecma262/#sec-typedarray-objects">Section 22.2</a> of the ECMAScript Language Specification.</p>
2335<h5>napi_create_dataview<span><a class="mark" href="#n_api_napi_create_dataview" id="n_api_napi_create_dataview">#</a></span></h5>
2336<div class="api_metadata">
2337<span>Added in: v8.3.0</span>
2338<span>N-API version: 1</span>
2339</div>
2340<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_dataview</span><span class="hljs-params">(napi_env env,
2341                                 <span class="hljs-type">size_t</span> byte_length,
2342                                 napi_value arraybuffer,
2343                                 <span class="hljs-type">size_t</span> byte_offset,
2344                                 napi_value* result)</span></code></pre>
2345<ul>
2346<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2347<li><code>[in] length</code>: Number of elements in the <code>DataView</code>.</li>
2348<li><code>[in] arraybuffer</code>: <code>ArrayBuffer</code> underlying the <code>DataView</code>.</li>
2349<li><code>[in] byte_offset</code>: The byte offset within the <code>ArrayBuffer</code> from which to
2350start projecting the <code>DataView</code>.</li>
2351<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>DataView</code>.</li>
2352</ul>
2353<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2354<p>This API creates a JavaScript <code>DataView</code> object over an existing <code>ArrayBuffer</code>.
2355<code>DataView</code> objects provide an array-like view over an underlying data buffer,
2356but one which allows items of different size and type in the <code>ArrayBuffer</code>.</p>
2357<p>It is required that <code>byte_length + byte_offset</code> is less than or equal to the
2358size in bytes of the array passed in. If not, a <code>RangeError</code> exception is
2359raised.</p>
2360<p>JavaScript <code>DataView</code> objects are described in
2361<a href="https://tc39.github.io/ecma262/#sec-dataview-objects">Section 24.3</a> of the ECMAScript Language Specification.</p>
2362<h4>Functions to convert from C types to Node-API<span><a class="mark" href="#n_api_functions_to_convert_from_c_types_to_node_api" id="n_api_functions_to_convert_from_c_types_to_node_api">#</a></span></h4>
2363<h5>napi_create_int32<span><a class="mark" href="#n_api_napi_create_int32" id="n_api_napi_create_int32">#</a></span></h5>
2364<div class="api_metadata">
2365<span>Added in: v8.4.0</span>
2366<span>N-API version: 1</span>
2367</div>
2368<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_int32</span><span class="hljs-params">(napi_env env, <span class="hljs-type">int32_t</span> value, napi_value* result)</span></code></pre>
2369<ul>
2370<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2371<li><code>[in] value</code>: Integer value to be represented in JavaScript.</li>
2372<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>number</code>.</li>
2373</ul>
2374<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2375<p>This API is used to convert from the C <code>int32_t</code> type to the JavaScript
2376<code>number</code> type.</p>
2377<p>The JavaScript <code>number</code> type is described in
2378<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p>
2379<h5>napi_create_uint32<span><a class="mark" href="#n_api_napi_create_uint32" id="n_api_napi_create_uint32">#</a></span></h5>
2380<div class="api_metadata">
2381<span>Added in: v8.4.0</span>
2382<span>N-API version: 1</span>
2383</div>
2384<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_uint32</span><span class="hljs-params">(napi_env env, <span class="hljs-type">uint32_t</span> value, napi_value* result)</span></code></pre>
2385<ul>
2386<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2387<li><code>[in] value</code>: Unsigned integer value to be represented in JavaScript.</li>
2388<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>number</code>.</li>
2389</ul>
2390<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2391<p>This API is used to convert from the C <code>uint32_t</code> type to the JavaScript
2392<code>number</code> type.</p>
2393<p>The JavaScript <code>number</code> type is described in
2394<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p>
2395<h5>napi_create_int64<span><a class="mark" href="#n_api_napi_create_int64" id="n_api_napi_create_int64">#</a></span></h5>
2396<div class="api_metadata">
2397<span>Added in: v8.4.0</span>
2398<span>N-API version: 1</span>
2399</div>
2400<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_int64</span><span class="hljs-params">(napi_env env, <span class="hljs-type">int64_t</span> value, napi_value* result)</span></code></pre>
2401<ul>
2402<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2403<li><code>[in] value</code>: Integer value to be represented in JavaScript.</li>
2404<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>number</code>.</li>
2405</ul>
2406<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2407<p>This API is used to convert from the C <code>int64_t</code> type to the JavaScript
2408<code>number</code> type.</p>
2409<p>The JavaScript <code>number</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a>
2410of the ECMAScript Language Specification. Note the complete range of <code>int64_t</code>
2411cannot be represented with full precision in JavaScript. Integer values
2412outside the range of <a href="https://tc39.github.io/ecma262/#sec-number.min_safe_integer"><code>Number.MIN_SAFE_INTEGER</code></a> <code>-(2**53 - 1)</code> -
2413<a href="https://tc39.github.io/ecma262/#sec-number.max_safe_integer"><code>Number.MAX_SAFE_INTEGER</code></a> <code>(2**53 - 1)</code> will lose precision.</p>
2414<h5>napi_create_double<span><a class="mark" href="#n_api_napi_create_double" id="n_api_napi_create_double">#</a></span></h5>
2415<div class="api_metadata">
2416<span>Added in: v8.4.0</span>
2417<span>N-API version: 1</span>
2418</div>
2419<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_double</span><span class="hljs-params">(napi_env env, <span class="hljs-type">double</span> value, napi_value* result)</span></code></pre>
2420<ul>
2421<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2422<li><code>[in] value</code>: Double-precision value to be represented in JavaScript.</li>
2423<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>number</code>.</li>
2424</ul>
2425<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2426<p>This API is used to convert from the C <code>double</code> type to the JavaScript
2427<code>number</code> type.</p>
2428<p>The JavaScript <code>number</code> type is described in
2429<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p>
2430<h5>napi_create_bigint_int64<span><a class="mark" href="#n_api_napi_create_bigint_int64" id="n_api_napi_create_bigint_int64">#</a></span></h5>
2431<div class="api_metadata">
2432<span>Added in: v10.7.0</span>
2433<span>N-API version: 6</span>
2434</div>
2435<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_bigint_int64</span><span class="hljs-params">(napi_env env,
2436                                     <span class="hljs-type">int64_t</span> value,
2437                                     napi_value* result)</span>;</code></pre>
2438<ul>
2439<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2440<li><code>[in] value</code>: Integer value to be represented in JavaScript.</li>
2441<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li>
2442</ul>
2443<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2444<p>This API converts the C <code>int64_t</code> type to the JavaScript <code>BigInt</code> type.</p>
2445<h5>napi_create_bigint_uint64<span><a class="mark" href="#n_api_napi_create_bigint_uint64" id="n_api_napi_create_bigint_uint64">#</a></span></h5>
2446<div class="api_metadata">
2447<span>Added in: v10.7.0</span>
2448<span>N-API version: 6</span>
2449</div>
2450<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_bigint_uint64</span><span class="hljs-params">(napi_env env,
2451                                      <span class="hljs-type">uint64_t</span> value,
2452                                      napi_value* result)</span>;</code></pre>
2453<ul>
2454<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2455<li><code>[in] value</code>: Unsigned integer value to be represented in JavaScript.</li>
2456<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li>
2457</ul>
2458<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2459<p>This API converts the C <code>uint64_t</code> type to the JavaScript <code>BigInt</code> type.</p>
2460<h5>napi_create_bigint_words<span><a class="mark" href="#n_api_napi_create_bigint_words" id="n_api_napi_create_bigint_words">#</a></span></h5>
2461<div class="api_metadata">
2462<span>Added in: v10.7.0</span>
2463<span>N-API version: 6</span>
2464</div>
2465<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_bigint_words</span><span class="hljs-params">(napi_env env,
2466                                     <span class="hljs-type">int</span> sign_bit,
2467                                     <span class="hljs-type">size_t</span> word_count,
2468                                     <span class="hljs-keyword">const</span> <span class="hljs-type">uint64_t</span>* words,
2469                                     napi_value* result)</span>;</code></pre>
2470<ul>
2471<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2472<li><code>[in] sign_bit</code>: Determines if the resulting <code>BigInt</code> will be positive or
2473negative.</li>
2474<li><code>[in] word_count</code>: The length of the <code>words</code> array.</li>
2475<li><code>[in] words</code>: An array of <code>uint64_t</code> little-endian 64-bit words.</li>
2476<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li>
2477</ul>
2478<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2479<p>This API converts an array of unsigned 64-bit words into a single <code>BigInt</code>
2480value.</p>
2481<p>The resulting <code>BigInt</code> is calculated as: (–1)<sup><code>sign_bit</code></sup> (<code>words[0]</code>
2482× (2<sup>64</sup>)<sup>0</sup> + <code>words[1]</code> × (2<sup>64</sup>)<sup>1</sup> + …)</p>
2483<h5>napi_create_string_latin1<span><a class="mark" href="#n_api_napi_create_string_latin1" id="n_api_napi_create_string_latin1">#</a></span></h5>
2484<div class="api_metadata">
2485<span>Added in: v8.0.0</span>
2486<span>N-API version: 1</span>
2487</div>
2488<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_string_latin1</span><span class="hljs-params">(napi_env env,
2489                                      <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* str,
2490                                      <span class="hljs-type">size_t</span> length,
2491                                      napi_value* result)</span>;</code></pre>
2492<ul>
2493<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2494<li><code>[in] str</code>: Character buffer representing an ISO-8859-1-encoded string.</li>
2495<li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it
2496is null-terminated.</li>
2497<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>string</code>.</li>
2498</ul>
2499<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2500<p>This API creates a JavaScript <code>string</code> value from an ISO-8859-1-encoded C
2501string. The native string is copied.</p>
2502<p>The JavaScript <code>string</code> type is described in
2503<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
2504<h5>napi_create_string_utf16<span><a class="mark" href="#n_api_napi_create_string_utf16" id="n_api_napi_create_string_utf16">#</a></span></h5>
2505<div class="api_metadata">
2506<span>Added in: v8.0.0</span>
2507<span>N-API version: 1</span>
2508</div>
2509<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_string_utf16</span><span class="hljs-params">(napi_env env,
2510                                     <span class="hljs-keyword">const</span> <span class="hljs-type">char16_t</span>* str,
2511                                     <span class="hljs-type">size_t</span> length,
2512                                     napi_value* result)</span></code></pre>
2513<ul>
2514<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2515<li><code>[in] str</code>: Character buffer representing a UTF16-LE-encoded string.</li>
2516<li><code>[in] length</code>: The length of the string in two-byte code units, or
2517<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
2518<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>string</code>.</li>
2519</ul>
2520<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2521<p>This API creates a JavaScript <code>string</code> value from a UTF16-LE-encoded C string.
2522The native string is copied.</p>
2523<p>The JavaScript <code>string</code> type is described in
2524<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
2525<h5>napi_create_string_utf8<span><a class="mark" href="#n_api_napi_create_string_utf8" id="n_api_napi_create_string_utf8">#</a></span></h5>
2526<div class="api_metadata">
2527<span>Added in: v8.0.0</span>
2528<span>N-API version: 1</span>
2529</div>
2530<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_string_utf8</span><span class="hljs-params">(napi_env env,
2531                                    <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* str,
2532                                    <span class="hljs-type">size_t</span> length,
2533                                    napi_value* result)</span></code></pre>
2534<ul>
2535<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2536<li><code>[in] str</code>: Character buffer representing a UTF8-encoded string.</li>
2537<li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it
2538is null-terminated.</li>
2539<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>string</code>.</li>
2540</ul>
2541<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2542<p>This API creates a JavaScript <code>string</code> value from a UTF8-encoded C string.
2543The native string is copied.</p>
2544<p>The JavaScript <code>string</code> type is described in
2545<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
2546<h4>Functions to convert from Node-API to C types<span><a class="mark" href="#n_api_functions_to_convert_from_node_api_to_c_types" id="n_api_functions_to_convert_from_node_api_to_c_types">#</a></span></h4>
2547<h5>napi_get_array_length<span><a class="mark" href="#n_api_napi_get_array_length" id="n_api_napi_get_array_length">#</a></span></h5>
2548<div class="api_metadata">
2549<span>Added in: v8.0.0</span>
2550<span>N-API version: 1</span>
2551</div>
2552<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_array_length</span><span class="hljs-params">(napi_env env,
2553                                  napi_value value,
2554                                  <span class="hljs-type">uint32_t</span>* result)</span></code></pre>
2555<ul>
2556<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2557<li><code>[in] value</code>: <code>napi_value</code> representing the JavaScript <code>Array</code> whose length is
2558being queried.</li>
2559<li><code>[out] result</code>: <code>uint32</code> representing length of the array.</li>
2560</ul>
2561<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2562<p>This API returns the length of an array.</p>
2563<p><code>Array</code> length is described in <a href="https://tc39.github.io/ecma262/#sec-properties-of-array-instances-length">Section 22.1.4.1</a> of the ECMAScript Language
2564Specification.</p>
2565<h5>napi_get_arraybuffer_info<span><a class="mark" href="#n_api_napi_get_arraybuffer_info" id="n_api_napi_get_arraybuffer_info">#</a></span></h5>
2566<div class="api_metadata">
2567<span>Added in: v8.0.0</span>
2568<span>N-API version: 1</span>
2569</div>
2570<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_arraybuffer_info</span><span class="hljs-params">(napi_env env,
2571                                      napi_value arraybuffer,
2572                                      <span class="hljs-type">void</span>** data,
2573                                      <span class="hljs-type">size_t</span>* byte_length)</span></code></pre>
2574<ul>
2575<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2576<li><code>[in] arraybuffer</code>: <code>napi_value</code> representing the <code>ArrayBuffer</code> being queried.</li>
2577<li><code>[out] data</code>: The underlying data buffer of the <code>ArrayBuffer</code>. If byte_length
2578is <code>0</code>, this may be <code>NULL</code> or any other pointer value.</li>
2579<li><code>[out] byte_length</code>: Length in bytes of the underlying data buffer.</li>
2580</ul>
2581<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2582<p>This API is used to retrieve the underlying data buffer of an <code>ArrayBuffer</code> and
2583its length.</p>
2584<p><em>WARNING</em>: Use caution while using this API. The lifetime of the underlying data
2585buffer is managed by the <code>ArrayBuffer</code> even after it's returned. A
2586possible safe way to use this API is in conjunction with
2587<a href="#n_api_napi_create_reference"><code>napi_create_reference</code></a>, which can be used to guarantee control over the
2588lifetime of the <code>ArrayBuffer</code>. It's also safe to use the returned data buffer
2589within the same callback as long as there are no calls to other APIs that might
2590trigger a GC.</p>
2591<h5>napi_get_buffer_info<span><a class="mark" href="#n_api_napi_get_buffer_info" id="n_api_napi_get_buffer_info">#</a></span></h5>
2592<div class="api_metadata">
2593<span>Added in: v8.0.0</span>
2594<span>N-API version: 1</span>
2595</div>
2596<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_buffer_info</span><span class="hljs-params">(napi_env env,
2597                                 napi_value value,
2598                                 <span class="hljs-type">void</span>** data,
2599                                 <span class="hljs-type">size_t</span>* length)</span></code></pre>
2600<ul>
2601<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2602<li><code>[in] value</code>: <code>napi_value</code> representing the <code>node::Buffer</code> being queried.</li>
2603<li><code>[out] data</code>: The underlying data buffer of the <code>node::Buffer</code>.
2604If length is <code>0</code>, this may be <code>NULL</code> or any other pointer value.</li>
2605<li><code>[out] length</code>: Length in bytes of the underlying data buffer.</li>
2606</ul>
2607<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2608<p>This API is used to retrieve the underlying data buffer of a <code>node::Buffer</code>
2609and it's length.</p>
2610<p><em>Warning</em>: Use caution while using this API since the underlying data buffer's
2611lifetime is not guaranteed if it's managed by the VM.</p>
2612<h5>napi_get_prototype<span><a class="mark" href="#n_api_napi_get_prototype" id="n_api_napi_get_prototype">#</a></span></h5>
2613<div class="api_metadata">
2614<span>Added in: v8.0.0</span>
2615<span>N-API version: 1</span>
2616</div>
2617<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_prototype</span><span class="hljs-params">(napi_env env,
2618                               napi_value object,
2619                               napi_value* result)</span></code></pre>
2620<ul>
2621<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2622<li><code>[in] object</code>: <code>napi_value</code> representing JavaScript <code>Object</code> whose prototype
2623to return. This returns the equivalent of <code>Object.getPrototypeOf</code> (which is
2624not the same as the function's <code>prototype</code> property).</li>
2625<li><code>[out] result</code>: <code>napi_value</code> representing prototype of the given object.</li>
2626</ul>
2627<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2628<h5>napi_get_typedarray_info<span><a class="mark" href="#n_api_napi_get_typedarray_info" id="n_api_napi_get_typedarray_info">#</a></span></h5>
2629<div class="api_metadata">
2630<span>Added in: v8.0.0</span>
2631<span>N-API version: 1</span>
2632</div>
2633<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_typedarray_info</span><span class="hljs-params">(napi_env env,
2634                                     napi_value typedarray,
2635                                     napi_typedarray_type* type,
2636                                     <span class="hljs-type">size_t</span>* length,
2637                                     <span class="hljs-type">void</span>** data,
2638                                     napi_value* arraybuffer,
2639                                     <span class="hljs-type">size_t</span>* byte_offset)</span></code></pre>
2640<ul>
2641<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2642<li><code>[in] typedarray</code>: <code>napi_value</code> representing the <code>TypedArray</code> whose
2643properties to query.</li>
2644<li><code>[out] type</code>: Scalar datatype of the elements within the <code>TypedArray</code>.</li>
2645<li><code>[out] length</code>: The number of elements in the <code>TypedArray</code>.</li>
2646<li><code>[out] data</code>: The data buffer underlying the <code>TypedArray</code> adjusted by
2647the <code>byte_offset</code> value so that it points to the first element in the
2648<code>TypedArray</code>. If the length of the array is <code>0</code>, this may be <code>NULL</code> or
2649any other pointer value.</li>
2650<li><code>[out] arraybuffer</code>: The <code>ArrayBuffer</code> underlying the <code>TypedArray</code>.</li>
2651<li><code>[out] byte_offset</code>: The byte offset within the underlying native array
2652at which the first element of the arrays is located. The value for the data
2653parameter has already been adjusted so that data points to the first element
2654in the array. Therefore, the first byte of the native array would be at
2655<code>data - byte_offset</code>.</li>
2656</ul>
2657<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2658<p>This API returns various properties of a typed array.</p>
2659<p><em>Warning</em>: Use caution while using this API since the underlying data buffer
2660is managed by the VM.</p>
2661<h5>napi_get_dataview_info<span><a class="mark" href="#n_api_napi_get_dataview_info" id="n_api_napi_get_dataview_info">#</a></span></h5>
2662<div class="api_metadata">
2663<span>Added in: v8.3.0</span>
2664<span>N-API version: 1</span>
2665</div>
2666<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_dataview_info</span><span class="hljs-params">(napi_env env,
2667                                   napi_value dataview,
2668                                   <span class="hljs-type">size_t</span>* byte_length,
2669                                   <span class="hljs-type">void</span>** data,
2670                                   napi_value* arraybuffer,
2671                                   <span class="hljs-type">size_t</span>* byte_offset)</span></code></pre>
2672<ul>
2673<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2674<li><code>[in] dataview</code>: <code>napi_value</code> representing the <code>DataView</code> whose
2675properties to query.</li>
2676<li><code>[out] byte_length</code>: Number of bytes in the <code>DataView</code>.</li>
2677<li><code>[out] data</code>: The data buffer underlying the <code>DataView</code>.
2678If byte_length is <code>0</code>, this may be <code>NULL</code> or any other pointer value.</li>
2679<li><code>[out] arraybuffer</code>: <code>ArrayBuffer</code> underlying the <code>DataView</code>.</li>
2680<li><code>[out] byte_offset</code>: The byte offset within the data buffer from which
2681to start projecting the <code>DataView</code>.</li>
2682</ul>
2683<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2684<p>This API returns various properties of a <code>DataView</code>.</p>
2685<h5>napi_get_date_value<span><a class="mark" href="#n_api_napi_get_date_value" id="n_api_napi_get_date_value">#</a></span></h5>
2686<div class="api_metadata">
2687<span>Added in: v11.11.0, v10.17.0</span>
2688<span>N-API version: 5</span>
2689</div>
2690<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_date_value</span><span class="hljs-params">(napi_env env,
2691                                napi_value value,
2692                                <span class="hljs-type">double</span>* result)</span></code></pre>
2693<ul>
2694<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2695<li><code>[in] value</code>: <code>napi_value</code> representing a JavaScript <code>Date</code>.</li>
2696<li><code>[out] result</code>: Time value as a <code>double</code> represented as milliseconds since
2697midnight at the beginning of 01 January, 1970 UTC.</li>
2698</ul>
2699<p>This API does not observe leap seconds; they are ignored, as
2700ECMAScript aligns with POSIX time specification.</p>
2701<p>Returns <code>napi_ok</code> if the API succeeded. If a non-date <code>napi_value</code> is passed
2702in it returns <code>napi_date_expected</code>.</p>
2703<p>This API returns the C double primitive of time value for the given JavaScript
2704<code>Date</code>.</p>
2705<h5>napi_get_value_bool<span><a class="mark" href="#n_api_napi_get_value_bool" id="n_api_napi_get_value_bool">#</a></span></h5>
2706<div class="api_metadata">
2707<span>Added in: v8.0.0</span>
2708<span>N-API version: 1</span>
2709</div>
2710<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_bool</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code></pre>
2711<ul>
2712<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2713<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Boolean</code>.</li>
2714<li><code>[out] result</code>: C boolean primitive equivalent of the given JavaScript
2715<code>Boolean</code>.</li>
2716</ul>
2717<p>Returns <code>napi_ok</code> if the API succeeded. If a non-boolean <code>napi_value</code> is
2718passed in it returns <code>napi_boolean_expected</code>.</p>
2719<p>This API returns the C boolean primitive equivalent of the given JavaScript
2720<code>Boolean</code>.</p>
2721<h5>napi_get_value_double<span><a class="mark" href="#n_api_napi_get_value_double" id="n_api_napi_get_value_double">#</a></span></h5>
2722<div class="api_metadata">
2723<span>Added in: v8.0.0</span>
2724<span>N-API version: 1</span>
2725</div>
2726<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_double</span><span class="hljs-params">(napi_env env,
2727                                  napi_value value,
2728                                  <span class="hljs-type">double</span>* result)</span></code></pre>
2729<ul>
2730<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2731<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>number</code>.</li>
2732<li><code>[out] result</code>: C double primitive equivalent of the given JavaScript
2733<code>number</code>.</li>
2734</ul>
2735<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code> is passed
2736in it returns <code>napi_number_expected</code>.</p>
2737<p>This API returns the C double primitive equivalent of the given JavaScript
2738<code>number</code>.</p>
2739<h5>napi_get_value_bigint_int64<span><a class="mark" href="#n_api_napi_get_value_bigint_int64" id="n_api_napi_get_value_bigint_int64">#</a></span></h5>
2740<div class="api_metadata">
2741<span>Added in: v10.7.0</span>
2742<span>N-API version: 6</span>
2743</div>
2744<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_bigint_int64</span><span class="hljs-params">(napi_env env,
2745                                        napi_value value,
2746                                        <span class="hljs-type">int64_t</span>* result,
2747                                        <span class="hljs-type">bool</span>* lossless)</span>;</code></pre>
2748<ul>
2749<li><code>[in] env</code>: The environment that the API is invoked under</li>
2750<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li>
2751<li><code>[out] result</code>: C <code>int64_t</code> primitive equivalent of the given JavaScript
2752<code>BigInt</code>.</li>
2753<li><code>[out] lossless</code>: Indicates whether the <code>BigInt</code> value was converted
2754losslessly.</li>
2755</ul>
2756<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>BigInt</code> is passed in it
2757returns <code>napi_bigint_expected</code>.</p>
2758<p>This API returns the C <code>int64_t</code> primitive equivalent of the given JavaScript
2759<code>BigInt</code>. If needed it will truncate the value, setting <code>lossless</code> to <code>false</code>.</p>
2760<h5>napi_get_value_bigint_uint64<span><a class="mark" href="#n_api_napi_get_value_bigint_uint64" id="n_api_napi_get_value_bigint_uint64">#</a></span></h5>
2761<div class="api_metadata">
2762<span>Added in: v10.7.0</span>
2763<span>N-API version: 6</span>
2764</div>
2765<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_bigint_uint64</span><span class="hljs-params">(napi_env env,
2766                                        napi_value value,
2767                                        <span class="hljs-type">uint64_t</span>* result,
2768                                        <span class="hljs-type">bool</span>* lossless)</span>;</code></pre>
2769<ul>
2770<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2771<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li>
2772<li><code>[out] result</code>: C <code>uint64_t</code> primitive equivalent of the given JavaScript
2773<code>BigInt</code>.</li>
2774<li><code>[out] lossless</code>: Indicates whether the <code>BigInt</code> value was converted
2775losslessly.</li>
2776</ul>
2777<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>BigInt</code> is passed in it
2778returns <code>napi_bigint_expected</code>.</p>
2779<p>This API returns the C <code>uint64_t</code> primitive equivalent of the given JavaScript
2780<code>BigInt</code>. If needed it will truncate the value, setting <code>lossless</code> to <code>false</code>.</p>
2781<h5>napi_get_value_bigint_words<span><a class="mark" href="#n_api_napi_get_value_bigint_words" id="n_api_napi_get_value_bigint_words">#</a></span></h5>
2782<div class="api_metadata">
2783<span>Added in: v10.7.0</span>
2784<span>N-API version: 6</span>
2785</div>
2786<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_bigint_words</span><span class="hljs-params">(napi_env env,
2787                                        napi_value value,
2788                                        <span class="hljs-type">int</span>* sign_bit,
2789                                        <span class="hljs-type">size_t</span>* word_count,
2790                                        <span class="hljs-type">uint64_t</span>* words)</span>;</code></pre>
2791<ul>
2792<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2793<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li>
2794<li><code>[out] sign_bit</code>: Integer representing if the JavaScript <code>BigInt</code> is positive
2795or negative.</li>
2796<li><code>[in/out] word_count</code>: Must be initialized to the length of the <code>words</code>
2797array. Upon return, it will be set to the actual number of words that
2798would be needed to store this <code>BigInt</code>.</li>
2799<li><code>[out] words</code>: Pointer to a pre-allocated 64-bit word array.</li>
2800</ul>
2801<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2802<p>This API converts a single <code>BigInt</code> value into a sign bit, 64-bit little-endian
2803array, and the number of elements in the array. <code>sign_bit</code> and <code>words</code> may be
2804both set to <code>NULL</code>, in order to get only <code>word_count</code>.</p>
2805<h5>napi_get_value_external<span><a class="mark" href="#n_api_napi_get_value_external" id="n_api_napi_get_value_external">#</a></span></h5>
2806<div class="api_metadata">
2807<span>Added in: v8.0.0</span>
2808<span>N-API version: 1</span>
2809</div>
2810<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_external</span><span class="hljs-params">(napi_env env,
2811                                    napi_value value,
2812                                    <span class="hljs-type">void</span>** result)</span></code></pre>
2813<ul>
2814<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2815<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript external value.</li>
2816<li><code>[out] result</code>: Pointer to the data wrapped by the JavaScript external value.</li>
2817</ul>
2818<p>Returns <code>napi_ok</code> if the API succeeded. If a non-external <code>napi_value</code> is
2819passed in it returns <code>napi_invalid_arg</code>.</p>
2820<p>This API retrieves the external data pointer that was previously passed to
2821<code>napi_create_external()</code>.</p>
2822<h5>napi_get_value_int32<span><a class="mark" href="#n_api_napi_get_value_int32" id="n_api_napi_get_value_int32">#</a></span></h5>
2823<div class="api_metadata">
2824<span>Added in: v8.0.0</span>
2825<span>N-API version: 1</span>
2826</div>
2827<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_int32</span><span class="hljs-params">(napi_env env,
2828                                 napi_value value,
2829                                 <span class="hljs-type">int32_t</span>* result)</span></code></pre>
2830<ul>
2831<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2832<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>number</code>.</li>
2833<li><code>[out] result</code>: C <code>int32</code> primitive equivalent of the given JavaScript
2834<code>number</code>.</li>
2835</ul>
2836<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
2837is passed in <code>napi_number_expected</code>.</p>
2838<p>This API returns the C <code>int32</code> primitive equivalent
2839of the given JavaScript <code>number</code>.</p>
2840<p>If the number exceeds the range of the 32 bit integer, then the result is
2841truncated to the equivalent of the bottom 32 bits. This can result in a large
2842positive number becoming a negative number if the value is > 2<sup>31</sup> - 1.</p>
2843<p>Non-finite number values (<code>NaN</code>, <code>+Infinity</code>, or <code>-Infinity</code>) set the
2844result to zero.</p>
2845<h5>napi_get_value_int64<span><a class="mark" href="#n_api_napi_get_value_int64" id="n_api_napi_get_value_int64">#</a></span></h5>
2846<div class="api_metadata">
2847<span>Added in: v8.0.0</span>
2848<span>N-API version: 1</span>
2849</div>
2850<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_int64</span><span class="hljs-params">(napi_env env,
2851                                 napi_value value,
2852                                 <span class="hljs-type">int64_t</span>* result)</span></code></pre>
2853<ul>
2854<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2855<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>number</code>.</li>
2856<li><code>[out] result</code>: C <code>int64</code> primitive equivalent of the given JavaScript
2857<code>number</code>.</li>
2858</ul>
2859<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
2860is passed in it returns <code>napi_number_expected</code>.</p>
2861<p>This API returns the C <code>int64</code> primitive equivalent of the given JavaScript
2862<code>number</code>.</p>
2863<p><code>number</code> values outside the range of <a href="https://tc39.github.io/ecma262/#sec-number.min_safe_integer"><code>Number.MIN_SAFE_INTEGER</code></a>
2864<code>-(2**53 - 1)</code> - <a href="https://tc39.github.io/ecma262/#sec-number.max_safe_integer"><code>Number.MAX_SAFE_INTEGER</code></a> <code>(2**53 - 1)</code> will lose
2865precision.</p>
2866<p>Non-finite number values (<code>NaN</code>, <code>+Infinity</code>, or <code>-Infinity</code>) set the
2867result to zero.</p>
2868<h5>napi_get_value_string_latin1<span><a class="mark" href="#n_api_napi_get_value_string_latin1" id="n_api_napi_get_value_string_latin1">#</a></span></h5>
2869<div class="api_metadata">
2870<span>Added in: v8.0.0</span>
2871<span>N-API version: 1</span>
2872</div>
2873<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_string_latin1</span><span class="hljs-params">(napi_env env,
2874                                         napi_value value,
2875                                         <span class="hljs-type">char</span>* buf,
2876                                         <span class="hljs-type">size_t</span> bufsize,
2877                                         <span class="hljs-type">size_t</span>* result)</span></code></pre>
2878<ul>
2879<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2880<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li>
2881<li><code>[in] buf</code>: Buffer to write the ISO-8859-1-encoded string into. If <code>NULL</code> is
2882passed in, the length of the string in bytes and excluding the null terminator
2883is returned in <code>result</code>.</li>
2884<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
2885insufficient, the returned string is truncated and null-terminated.</li>
2886<li><code>[out] result</code>: Number of bytes copied into the buffer, excluding the null
2887terminator.</li>
2888</ul>
2889<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>string</code> <code>napi_value</code>
2890is passed in it returns <code>napi_string_expected</code>.</p>
2891<p>This API returns the ISO-8859-1-encoded string corresponding the value passed
2892in.</p>
2893<h5>napi_get_value_string_utf8<span><a class="mark" href="#n_api_napi_get_value_string_utf8" id="n_api_napi_get_value_string_utf8">#</a></span></h5>
2894<div class="api_metadata">
2895<span>Added in: v8.0.0</span>
2896<span>N-API version: 1</span>
2897</div>
2898<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_string_utf8</span><span class="hljs-params">(napi_env env,
2899                                       napi_value value,
2900                                       <span class="hljs-type">char</span>* buf,
2901                                       <span class="hljs-type">size_t</span> bufsize,
2902                                       <span class="hljs-type">size_t</span>* result)</span></code></pre>
2903<ul>
2904<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2905<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li>
2906<li><code>[in] buf</code>: Buffer to write the UTF8-encoded string into. If <code>NULL</code> is passed
2907in, the length of the string in bytes and excluding the null terminator is
2908returned in <code>result</code>.</li>
2909<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
2910insufficient, the returned string is truncated and null-terminated.</li>
2911<li><code>[out] result</code>: Number of bytes copied into the buffer, excluding the null
2912terminator.</li>
2913</ul>
2914<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>string</code> <code>napi_value</code>
2915is passed in it returns <code>napi_string_expected</code>.</p>
2916<p>This API returns the UTF8-encoded string corresponding the value passed in.</p>
2917<h5>napi_get_value_string_utf16<span><a class="mark" href="#n_api_napi_get_value_string_utf16" id="n_api_napi_get_value_string_utf16">#</a></span></h5>
2918<div class="api_metadata">
2919<span>Added in: v8.0.0</span>
2920<span>N-API version: 1</span>
2921</div>
2922<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_string_utf16</span><span class="hljs-params">(napi_env env,
2923                                        napi_value value,
2924                                        <span class="hljs-type">char16_t</span>* buf,
2925                                        <span class="hljs-type">size_t</span> bufsize,
2926                                        <span class="hljs-type">size_t</span>* result)</span></code></pre>
2927<ul>
2928<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2929<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li>
2930<li><code>[in] buf</code>: Buffer to write the UTF16-LE-encoded string into. If <code>NULL</code> is
2931passed in, the length of the string in 2-byte code units and excluding the
2932null terminator is returned.</li>
2933<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
2934insufficient, the returned string is truncated and null-terminated.</li>
2935<li><code>[out] result</code>: Number of 2-byte code units copied into the buffer, excluding
2936the null terminator.</li>
2937</ul>
2938<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>string</code> <code>napi_value</code>
2939is passed in it returns <code>napi_string_expected</code>.</p>
2940<p>This API returns the UTF16-encoded string corresponding the value passed in.</p>
2941<h5>napi_get_value_uint32<span><a class="mark" href="#n_api_napi_get_value_uint32" id="n_api_napi_get_value_uint32">#</a></span></h5>
2942<div class="api_metadata">
2943<span>Added in: v8.0.0</span>
2944<span>N-API version: 1</span>
2945</div>
2946<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_uint32</span><span class="hljs-params">(napi_env env,
2947                                  napi_value value,
2948                                  <span class="hljs-type">uint32_t</span>* result)</span></code></pre>
2949<ul>
2950<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2951<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>number</code>.</li>
2952<li><code>[out] result</code>: C primitive equivalent of the given <code>napi_value</code> as a
2953<code>uint32_t</code>.</li>
2954</ul>
2955<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
2956is passed in it returns <code>napi_number_expected</code>.</p>
2957<p>This API returns the C primitive equivalent of the given <code>napi_value</code> as a
2958<code>uint32_t</code>.</p>
2959<h4>Functions to get global instances<span><a class="mark" href="#n_api_functions_to_get_global_instances" id="n_api_functions_to_get_global_instances">#</a></span></h4>
2960<h5>napi_get_boolean<span><a class="mark" href="#n_api_napi_get_boolean" id="n_api_napi_get_boolean">#</a></span></h5>
2961<div class="api_metadata">
2962<span>Added in: v8.0.0</span>
2963<span>N-API version: 1</span>
2964</div>
2965<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_boolean</span><span class="hljs-params">(napi_env env, <span class="hljs-type">bool</span> value, napi_value* result)</span></code></pre>
2966<ul>
2967<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2968<li><code>[in] value</code>: The value of the boolean to retrieve.</li>
2969<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>Boolean</code> singleton to
2970retrieve.</li>
2971</ul>
2972<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2973<p>This API is used to return the JavaScript singleton object that is used to
2974represent the given boolean value.</p>
2975<h5>napi_get_global<span><a class="mark" href="#n_api_napi_get_global" id="n_api_napi_get_global">#</a></span></h5>
2976<div class="api_metadata">
2977<span>Added in: v8.0.0</span>
2978<span>N-API version: 1</span>
2979</div>
2980<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_global</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code></pre>
2981<ul>
2982<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2983<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>global</code> object.</li>
2984</ul>
2985<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2986<p>This API returns the <code>global</code> object.</p>
2987<h5>napi_get_null<span><a class="mark" href="#n_api_napi_get_null" id="n_api_napi_get_null">#</a></span></h5>
2988<div class="api_metadata">
2989<span>Added in: v8.0.0</span>
2990<span>N-API version: 1</span>
2991</div>
2992<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_null</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code></pre>
2993<ul>
2994<li><code>[in] env</code>: The environment that the API is invoked under.</li>
2995<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>null</code> object.</li>
2996</ul>
2997<p>Returns <code>napi_ok</code> if the API succeeded.</p>
2998<p>This API returns the <code>null</code> object.</p>
2999<h5>napi_get_undefined<span><a class="mark" href="#n_api_napi_get_undefined" id="n_api_napi_get_undefined">#</a></span></h5>
3000<div class="api_metadata">
3001<span>Added in: v8.0.0</span>
3002<span>N-API version: 1</span>
3003</div>
3004<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_undefined</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code></pre>
3005<ul>
3006<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3007<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript Undefined value.</li>
3008</ul>
3009<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3010<p>This API returns the Undefined object.</p>
3011</section><section><h3>Working with JavaScript values and abstract operations<span><a class="mark" href="#n_api_working_with_javascript_values_and_abstract_operations" id="n_api_working_with_javascript_values_and_abstract_operations">#</a></span></h3>
3012<p>Node-API exposes a set of APIs to perform some abstract operations on JavaScript
3013values. Some of these operations are documented under <a href="https://tc39.github.io/ecma262/#sec-abstract-operations">Section 7</a>
3014of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
3015<p>These APIs support doing one of the following:</p>
3016<ol>
3017<li>Coerce JavaScript values to specific JavaScript types (such as <code>number</code> or
3018<code>string</code>).</li>
3019<li>Check the type of a JavaScript value.</li>
3020<li>Check for equality between two JavaScript values.</li>
3021</ol>
3022<h4>napi_coerce_to_bool<span><a class="mark" href="#n_api_napi_coerce_to_bool" id="n_api_napi_coerce_to_bool">#</a></span></h4>
3023<div class="api_metadata">
3024<span>Added in: v8.0.0</span>
3025<span>N-API version: 1</span>
3026</div>
3027<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_coerce_to_bool</span><span class="hljs-params">(napi_env env,
3028                                napi_value value,
3029                                napi_value* result)</span></code></pre>
3030<ul>
3031<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3032<li><code>[in] value</code>: The JavaScript value to coerce.</li>
3033<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Boolean</code>.</li>
3034</ul>
3035<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3036<p>This API implements the abstract operation <code>ToBoolean()</code> as defined in
3037<a href="https://tc39.github.io/ecma262/#sec-toboolean">Section 7.1.2</a> of the ECMAScript Language Specification.
3038This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p>
3039<h4>napi_coerce_to_number<span><a class="mark" href="#n_api_napi_coerce_to_number" id="n_api_napi_coerce_to_number">#</a></span></h4>
3040<div class="api_metadata">
3041<span>Added in: v8.0.0</span>
3042<span>N-API version: 1</span>
3043</div>
3044<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_coerce_to_number</span><span class="hljs-params">(napi_env env,
3045                                  napi_value value,
3046                                  napi_value* result)</span></code></pre>
3047<ul>
3048<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3049<li><code>[in] value</code>: The JavaScript value to coerce.</li>
3050<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>number</code>.</li>
3051</ul>
3052<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3053<p>This API implements the abstract operation <code>ToNumber()</code> as defined in
3054<a href="https://tc39.github.io/ecma262/#sec-tonumber">Section 7.1.3</a> of the ECMAScript Language Specification.
3055This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p>
3056<h4>napi_coerce_to_object<span><a class="mark" href="#n_api_napi_coerce_to_object" id="n_api_napi_coerce_to_object">#</a></span></h4>
3057<div class="api_metadata">
3058<span>Added in: v8.0.0</span>
3059<span>N-API version: 1</span>
3060</div>
3061<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_coerce_to_object</span><span class="hljs-params">(napi_env env,
3062                                  napi_value value,
3063                                  napi_value* result)</span></code></pre>
3064<ul>
3065<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3066<li><code>[in] value</code>: The JavaScript value to coerce.</li>
3067<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Object</code>.</li>
3068</ul>
3069<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3070<p>This API implements the abstract operation <code>ToObject()</code> as defined in
3071<a href="https://tc39.github.io/ecma262/#sec-toobject">Section 7.1.13</a> of the ECMAScript Language Specification.
3072This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p>
3073<h4>napi_coerce_to_string<span><a class="mark" href="#n_api_napi_coerce_to_string" id="n_api_napi_coerce_to_string">#</a></span></h4>
3074<div class="api_metadata">
3075<span>Added in: v8.0.0</span>
3076<span>N-API version: 1</span>
3077</div>
3078<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_coerce_to_string</span><span class="hljs-params">(napi_env env,
3079                                  napi_value value,
3080                                  napi_value* result)</span></code></pre>
3081<ul>
3082<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3083<li><code>[in] value</code>: The JavaScript value to coerce.</li>
3084<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>string</code>.</li>
3085</ul>
3086<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3087<p>This API implements the abstract operation <code>ToString()</code> as defined in
3088<a href="https://tc39.github.io/ecma262/#sec-toobject">Section 7.1.13</a> of the ECMAScript Language Specification.
3089This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p>
3090<h4>napi_typeof<span><a class="mark" href="#n_api_napi_typeof" id="n_api_napi_typeof">#</a></span></h4>
3091<div class="api_metadata">
3092<span>Added in: v8.0.0</span>
3093<span>N-API version: 1</span>
3094</div>
3095<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_typeof</span><span class="hljs-params">(napi_env env, napi_value value, napi_valuetype* result)</span></code></pre>
3096<ul>
3097<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3098<li><code>[in] value</code>: The JavaScript value whose type to query.</li>
3099<li><code>[out] result</code>: The type of the JavaScript value.</li>
3100</ul>
3101<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3102<ul>
3103<li><code>napi_invalid_arg</code> if the type of <code>value</code> is not a known ECMAScript type and
3104<code>value</code> is not an External value.</li>
3105</ul>
3106<p>This API represents behavior similar to invoking the <code>typeof</code> Operator on
3107the object as defined in <a href="https://tc39.github.io/ecma262/#sec-typeof-operator">Section 12.5.5</a> of the ECMAScript Language
3108Specification. However, there are some differences:</p>
3109<ol>
3110<li>It has support for detecting an External value.</li>
3111<li>It detects <code>null</code> as a separate type, while ECMAScript <code>typeof</code> would detect
3112<code>object</code>.</li>
3113</ol>
3114<p>If <code>value</code> has a type that is invalid, an error is returned.</p>
3115<h4>napi_instanceof<span><a class="mark" href="#n_api_napi_instanceof" id="n_api_napi_instanceof">#</a></span></h4>
3116<div class="api_metadata">
3117<span>Added in: v8.0.0</span>
3118<span>N-API version: 1</span>
3119</div>
3120<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_instanceof</span><span class="hljs-params">(napi_env env,
3121                            napi_value object,
3122                            napi_value constructor,
3123                            <span class="hljs-type">bool</span>* result)</span></code></pre>
3124<ul>
3125<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3126<li><code>[in] object</code>: The JavaScript value to check.</li>
3127<li><code>[in] constructor</code>: The JavaScript function object of the constructor function
3128to check against.</li>
3129<li><code>[out] result</code>: Boolean that is set to true if <code>object instanceof constructor</code>
3130is true.</li>
3131</ul>
3132<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3133<p>This API represents invoking the <code>instanceof</code> Operator on the object as
3134defined in <a href="https://tc39.github.io/ecma262/#sec-instanceofoperator">Section 12.10.4</a> of the ECMAScript Language Specification.</p>
3135<h4>napi_is_array<span><a class="mark" href="#n_api_napi_is_array" id="n_api_napi_is_array">#</a></span></h4>
3136<div class="api_metadata">
3137<span>Added in: v8.0.0</span>
3138<span>N-API version: 1</span>
3139</div>
3140<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_array</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code></pre>
3141<ul>
3142<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3143<li><code>[in] value</code>: The JavaScript value to check.</li>
3144<li><code>[out] result</code>: Whether the given object is an array.</li>
3145</ul>
3146<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3147<p>This API represents invoking the <code>IsArray</code> operation on the object
3148as defined in <a href="https://tc39.github.io/ecma262/#sec-isarray">Section 7.2.2</a> of the ECMAScript Language Specification.</p>
3149<h4>napi_is_arraybuffer<span><a class="mark" href="#n_api_napi_is_arraybuffer" id="n_api_napi_is_arraybuffer">#</a></span></h4>
3150<div class="api_metadata">
3151<span>Added in: v8.0.0</span>
3152<span>N-API version: 1</span>
3153</div>
3154<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_arraybuffer</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code></pre>
3155<ul>
3156<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3157<li><code>[in] value</code>: The JavaScript value to check.</li>
3158<li><code>[out] result</code>: Whether the given object is an <code>ArrayBuffer</code>.</li>
3159</ul>
3160<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3161<p>This API checks if the <code>Object</code> passed in is an array buffer.</p>
3162<h4>napi_is_buffer<span><a class="mark" href="#n_api_napi_is_buffer" id="n_api_napi_is_buffer">#</a></span></h4>
3163<div class="api_metadata">
3164<span>Added in: v8.0.0</span>
3165<span>N-API version: 1</span>
3166</div>
3167<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_buffer</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code></pre>
3168<ul>
3169<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3170<li><code>[in] value</code>: The JavaScript value to check.</li>
3171<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>node::Buffer</code>
3172object.</li>
3173</ul>
3174<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3175<p>This API checks if the <code>Object</code> passed in is a buffer.</p>
3176<h4>napi_is_date<span><a class="mark" href="#n_api_napi_is_date" id="n_api_napi_is_date">#</a></span></h4>
3177<div class="api_metadata">
3178<span>Added in: v11.11.0, v10.17.0</span>
3179<span>N-API version: 5</span>
3180</div>
3181<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_date</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code></pre>
3182<ul>
3183<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3184<li><code>[in] value</code>: The JavaScript value to check.</li>
3185<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a JavaScript <code>Date</code>
3186object.</li>
3187</ul>
3188<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3189<p>This API checks if the <code>Object</code> passed in is a date.</p>
3190<h4>napi_is_error<span><a class="mark" href="#n_api_napi_is_error_1" id="n_api_napi_is_error_1">#</a></span></h4>
3191<div class="api_metadata">
3192<span>Added in: v8.0.0</span>
3193<span>N-API version: 1</span>
3194</div>
3195<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_error</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code></pre>
3196<ul>
3197<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3198<li><code>[in] value</code>: The JavaScript value to check.</li>
3199<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents an <code>Error</code> object.</li>
3200</ul>
3201<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3202<p>This API checks if the <code>Object</code> passed in is an <code>Error</code>.</p>
3203<h4>napi_is_typedarray<span><a class="mark" href="#n_api_napi_is_typedarray" id="n_api_napi_is_typedarray">#</a></span></h4>
3204<div class="api_metadata">
3205<span>Added in: v8.0.0</span>
3206<span>N-API version: 1</span>
3207</div>
3208<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_typedarray</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code></pre>
3209<ul>
3210<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3211<li><code>[in] value</code>: The JavaScript value to check.</li>
3212<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>TypedArray</code>.</li>
3213</ul>
3214<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3215<p>This API checks if the <code>Object</code> passed in is a typed array.</p>
3216<h4>napi_is_dataview<span><a class="mark" href="#n_api_napi_is_dataview" id="n_api_napi_is_dataview">#</a></span></h4>
3217<div class="api_metadata">
3218<span>Added in: v8.3.0</span>
3219<span>N-API version: 1</span>
3220</div>
3221<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_dataview</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code></pre>
3222<ul>
3223<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3224<li><code>[in] value</code>: The JavaScript value to check.</li>
3225<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>DataView</code>.</li>
3226</ul>
3227<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3228<p>This API checks if the <code>Object</code> passed in is a <code>DataView</code>.</p>
3229<h4>napi_strict_equals<span><a class="mark" href="#n_api_napi_strict_equals" id="n_api_napi_strict_equals">#</a></span></h4>
3230<div class="api_metadata">
3231<span>Added in: v8.0.0</span>
3232<span>N-API version: 1</span>
3233</div>
3234<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_strict_equals</span><span class="hljs-params">(napi_env env,
3235                               napi_value lhs,
3236                               napi_value rhs,
3237                               <span class="hljs-type">bool</span>* result)</span></code></pre>
3238<ul>
3239<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3240<li><code>[in] lhs</code>: The JavaScript value to check.</li>
3241<li><code>[in] rhs</code>: The JavaScript value to check against.</li>
3242<li><code>[out] result</code>: Whether the two <code>napi_value</code> objects are equal.</li>
3243</ul>
3244<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3245<p>This API represents the invocation of the Strict Equality algorithm as
3246defined in <a href="https://tc39.github.io/ecma262/#sec-strict-equality-comparison">Section 7.2.14</a> of the ECMAScript Language Specification.</p>
3247<h4>napi_detach_arraybuffer<span><a class="mark" href="#n_api_napi_detach_arraybuffer" id="n_api_napi_detach_arraybuffer">#</a></span></h4>
3248<div class="api_metadata">
3249<span>Added in: v13.0.0, v12.16.0, v10.22.0</span>
3250<span>N-API version: 7</span>
3251</div>
3252<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_detach_arraybuffer</span><span class="hljs-params">(napi_env env,
3253                                    napi_value arraybuffer)</span></code></pre>
3254<ul>
3255<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3256<li><code>[in] arraybuffer</code>: The JavaScript <code>ArrayBuffer</code> to be detached.</li>
3257</ul>
3258<p>Returns <code>napi_ok</code> if the API succeeded. If a non-detachable <code>ArrayBuffer</code> is
3259passed in it returns <code>napi_detachable_arraybuffer_expected</code>.</p>
3260<p>Generally, an <code>ArrayBuffer</code> is non-detachable if it has been detached before.
3261The engine may impose additional conditions on whether an <code>ArrayBuffer</code> is
3262detachable. For example, V8 requires that the <code>ArrayBuffer</code> be external,
3263that is, created with <a href="#n_api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a>.</p>
3264<p>This API represents the invocation of the <code>ArrayBuffer</code> detach operation as
3265defined in <a href="https://tc39.es/ecma262/#sec-detacharraybuffer">Section 24.1.1.3</a> of the ECMAScript Language Specification.</p>
3266<h4>napi_is_detached_arraybuffer<span><a class="mark" href="#n_api_napi_is_detached_arraybuffer" id="n_api_napi_is_detached_arraybuffer">#</a></span></h4>
3267<div class="api_metadata">
3268<span>Added in: v13.3.0, v12.16.0, v10.22.0</span>
3269<span>N-API version: 7</span>
3270</div>
3271<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_detached_arraybuffer</span><span class="hljs-params">(napi_env env,
3272                                         napi_value arraybuffer,
3273                                         <span class="hljs-type">bool</span>* result)</span></code></pre>
3274<ul>
3275<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3276<li><code>[in] arraybuffer</code>: The JavaScript <code>ArrayBuffer</code> to be checked.</li>
3277<li><code>[out] result</code>: Whether the <code>arraybuffer</code> is detached.</li>
3278</ul>
3279<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3280<p>The <code>ArrayBuffer</code> is considered detached if its internal data is <code>null</code>.</p>
3281<p>This API represents the invocation of the <code>ArrayBuffer</code> <code>IsDetachedBuffer</code>
3282operation as defined in <a href="https://tc39.es/ecma262/#sec-isdetachedbuffer">Section 24.1.1.2</a> of the ECMAScript Language
3283Specification.</p>
3284</section><section><h3>Working with JavaScript properties<span><a class="mark" href="#n_api_working_with_javascript_properties" id="n_api_working_with_javascript_properties">#</a></span></h3>
3285<p>Node-API exposes a set of APIs to get and set properties on JavaScript
3286objects. Some of these types are documented under <a href="https://tc39.github.io/ecma262/#sec-abstract-operations">Section 7</a> of the
3287<a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
3288<p>Properties in JavaScript are represented as a tuple of a key and a value.
3289Fundamentally, all property keys in Node-API can be represented in one of the
3290following forms:</p>
3291<ul>
3292<li>Named: a simple UTF8-encoded string</li>
3293<li>Integer-Indexed: an index value represented by <code>uint32_t</code></li>
3294<li>JavaScript value: these are represented in Node-API by <code>napi_value</code>. This can
3295be a <code>napi_value</code> representing a <code>string</code>, <code>number</code>, or <code>symbol</code>.</li>
3296</ul>
3297<p>Node-API values are represented by the type <code>napi_value</code>.
3298Any Node-API call that requires a JavaScript value takes in a <code>napi_value</code>.
3299However, it's the caller's responsibility to make sure that the
3300<code>napi_value</code> in question is of the JavaScript type expected by the API.</p>
3301<p>The APIs documented in this section provide a simple interface to
3302get and set properties on arbitrary JavaScript objects represented by
3303<code>napi_value</code>.</p>
3304<p>For instance, consider the following JavaScript code snippet:</p>
3305<pre><code class="language-js"><span class="hljs-keyword">const</span> obj = {};
3306obj.<span class="hljs-property">myProp</span> = <span class="hljs-number">123</span>;</code></pre>
3307<p>The equivalent can be done using Node-API values with the following snippet:</p>
3308<pre><code class="language-c">napi_status status = napi_generic_failure;
3309
3310<span class="hljs-comment">// const obj = {}</span>
3311napi_value obj, value;
3312status = napi_create_object(env, &#x26;obj);
3313<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
3314
3315<span class="hljs-comment">// Create a napi_value for 123</span>
3316status = napi_create_int32(env, <span class="hljs-number">123</span>, &#x26;value);
3317<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
3318
3319<span class="hljs-comment">// obj.myProp = 123</span>
3320status = napi_set_named_property(env, obj, <span class="hljs-string">"myProp"</span>, value);
3321<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code></pre>
3322<p>Indexed properties can be set in a similar manner. Consider the following
3323JavaScript snippet:</p>
3324<pre><code class="language-js"><span class="hljs-keyword">const</span> arr = [];
3325arr[<span class="hljs-number">123</span>] = <span class="hljs-string">'hello'</span>;</code></pre>
3326<p>The equivalent can be done using Node-API values with the following snippet:</p>
3327<pre><code class="language-c">napi_status status = napi_generic_failure;
3328
3329<span class="hljs-comment">// const arr = [];</span>
3330napi_value arr, value;
3331status = napi_create_array(env, &#x26;arr);
3332<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
3333
3334<span class="hljs-comment">// Create a napi_value for 'hello'</span>
3335status = napi_create_string_utf8(env, <span class="hljs-string">"hello"</span>, NAPI_AUTO_LENGTH, &#x26;value);
3336<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
3337
3338<span class="hljs-comment">// arr[123] = 'hello';</span>
3339status = napi_set_element(env, arr, <span class="hljs-number">123</span>, value);
3340<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code></pre>
3341<p>Properties can be retrieved using the APIs described in this section.
3342Consider the following JavaScript snippet:</p>
3343<pre><code class="language-js"><span class="hljs-keyword">const</span> arr = [];
3344<span class="hljs-keyword">const</span> value = arr[<span class="hljs-number">123</span>];</code></pre>
3345<p>The following is the approximate equivalent of the Node-API counterpart:</p>
3346<pre><code class="language-c">napi_status status = napi_generic_failure;
3347
3348<span class="hljs-comment">// const arr = []</span>
3349napi_value arr, value;
3350status = napi_create_array(env, &#x26;arr);
3351<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
3352
3353<span class="hljs-comment">// const value = arr[123]</span>
3354status = napi_get_element(env, arr, <span class="hljs-number">123</span>, &#x26;value);
3355<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code></pre>
3356<p>Finally, multiple properties can also be defined on an object for performance
3357reasons. Consider the following JavaScript:</p>
3358<pre><code class="language-js"><span class="hljs-keyword">const</span> obj = {};
3359<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperties</span>(obj, {
3360  <span class="hljs-string">'foo'</span>: { <span class="hljs-attr">value</span>: <span class="hljs-number">123</span>, <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span> },
3361  <span class="hljs-string">'bar'</span>: { <span class="hljs-attr">value</span>: <span class="hljs-number">456</span>, <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span> }
3362});</code></pre>
3363<p>The following is the approximate equivalent of the Node-API counterpart:</p>
3364<pre><code class="language-c">napi_status status = napi_status_generic_failure;
3365
3366<span class="hljs-comment">// const obj = {};</span>
3367napi_value obj;
3368status = napi_create_object(env, &#x26;obj);
3369<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
3370
3371<span class="hljs-comment">// Create napi_values for 123 and 456</span>
3372napi_value fooValue, barValue;
3373status = napi_create_int32(env, <span class="hljs-number">123</span>, &#x26;fooValue);
3374<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
3375status = napi_create_int32(env, <span class="hljs-number">456</span>, &#x26;barValue);
3376<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
3377
3378<span class="hljs-comment">// Set the properties</span>
3379napi_property_descriptor descriptors[] = {
3380  { <span class="hljs-string">"foo"</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, fooValue, napi_writable | napi_configurable, <span class="hljs-literal">NULL</span> },
3381  { <span class="hljs-string">"bar"</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, barValue, napi_writable | napi_configurable, <span class="hljs-literal">NULL</span> }
3382}
3383status = napi_define_properties(env,
3384                                obj,
3385                                <span class="hljs-keyword">sizeof</span>(descriptors) / <span class="hljs-keyword">sizeof</span>(descriptors[<span class="hljs-number">0</span>]),
3386                                descriptors);
3387<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code></pre>
3388<h4>Structures<span><a class="mark" href="#n_api_structures" id="n_api_structures">#</a></span></h4>
3389<h5>napi_property_attributes<span><a class="mark" href="#n_api_napi_property_attributes" id="n_api_napi_property_attributes">#</a></span></h5>
3390<div class="api_metadata">
3391<details class="changelog"><summary>History</summary>
3392<table>
3393<tbody><tr><th>Version</th><th>Changes</th></tr>
3394<tr><td>v14.12.0</td>
3395<td><p>added <code>napi_default_method</code> and <code>napi_default_property</code>.</p></td></tr>
3396</tbody></table>
3397</details>
3398</div>
3399<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
3400  napi_default = <span class="hljs-number">0</span>,
3401  napi_writable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">0</span>,
3402  napi_enumerable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">1</span>,
3403  napi_configurable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">2</span>,
3404
3405  <span class="hljs-comment">// Used with napi_define_class to distinguish static properties</span>
3406  <span class="hljs-comment">// from instance properties. Ignored by napi_define_properties.</span>
3407  napi_static = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">10</span>,
3408
3409  <span class="hljs-comment">// Default for class methods.</span>
3410  napi_default_method = napi_writable | napi_configurable,
3411
3412  <span class="hljs-comment">// Default for object properties, like in JS obj[prop].</span>
3413  napi_default_jsproperty = napi_writable |
3414                          napi_enumerable |
3415                          napi_configurable,
3416} napi_property_attributes;</code></pre>
3417<p><code>napi_property_attributes</code> are flags used to control the behavior of properties
3418set on a JavaScript object. Other than <code>napi_static</code> they correspond to the
3419attributes listed in <a href="https://tc39.github.io/ecma262/#table-2">Section 6.1.7.1</a>
3420of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.
3421They can be one or more of the following bitflags:</p>
3422<ul>
3423<li><code>napi_default</code>: No explicit attributes are set on the property. By default, a
3424property is read only, not enumerable and not configurable.</li>
3425<li><code>napi_writable</code>: The property is writable.</li>
3426<li><code>napi_enumerable</code>: The property is enumerable.</li>
3427<li><code>napi_configurable</code>: The property is configurable as defined in
3428<a href="https://tc39.github.io/ecma262/#table-2">Section 6.1.7.1</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</li>
3429<li><code>napi_static</code>: The property will be defined as a static property on a class as
3430opposed to an instance property, which is the default. This is used only by
3431<a href="#n_api_napi_define_class"><code>napi_define_class</code></a>. It is ignored by <code>napi_define_properties</code>.</li>
3432<li><code>napi_default_method</code>: Like a method in a JS class, the property is
3433configurable and writeable, but not enumerable.</li>
3434<li><code>napi_default_jsproperty</code>: Like a property set via assignment in JavaScript,
3435the property is writable, enumerable, and configurable.</li>
3436</ul>
3437<h5>napi_property_descriptor<span><a class="mark" href="#n_api_napi_property_descriptor" id="n_api_napi_property_descriptor">#</a></span></h5>
3438<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
3439  <span class="hljs-comment">// One of utf8name or name should be NULL.</span>
3440  <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* utf8name;
3441  napi_value name;
3442
3443  napi_callback method;
3444  napi_callback getter;
3445  napi_callback setter;
3446  napi_value value;
3447
3448  napi_property_attributes attributes;
3449  <span class="hljs-type">void</span>* data;
3450} napi_property_descriptor;</code></pre>
3451<ul>
3452<li><code>utf8name</code>: Optional string describing the key for the property,
3453encoded as UTF8. One of <code>utf8name</code> or <code>name</code> must be provided for the
3454property.</li>
3455<li><code>name</code>: Optional <code>napi_value</code> that points to a JavaScript string or symbol
3456to be used as the key for the property. One of <code>utf8name</code> or <code>name</code> must
3457be provided for the property.</li>
3458<li><code>value</code>: The value that's retrieved by a get access of the property if the
3459property is a data property. If this is passed in, set <code>getter</code>, <code>setter</code>,
3460<code>method</code> and <code>data</code> to <code>NULL</code> (since these members won't be used).</li>
3461<li><code>getter</code>: A function to call when a get access of the property is performed.
3462If this is passed in, set <code>value</code> and <code>method</code> to <code>NULL</code> (since these members
3463won't be used). The given function is called implicitly by the runtime when
3464the property is accessed from JavaScript code (or if a get on the property is
3465performed using a Node-API call). <a href="#n_api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
3466<li><code>setter</code>: A function to call when a set access of the property is performed.
3467If this is passed in, set <code>value</code> and <code>method</code> to <code>NULL</code> (since these members
3468won't be used). The given function is called implicitly by the runtime when
3469the property is set from JavaScript code (or if a set on the property is
3470performed using a Node-API call). <a href="#n_api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
3471<li><code>method</code>: Set this to make the property descriptor object's <code>value</code>
3472property to be a JavaScript function represented by <code>method</code>. If this is
3473passed in, set <code>value</code>, <code>getter</code> and <code>setter</code> to <code>NULL</code> (since these members
3474won't be used). <a href="#n_api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
3475<li><code>attributes</code>: The attributes associated with the particular property. See
3476<a href="#n_api_napi_property_attributes"><code>napi_property_attributes</code></a>.</li>
3477<li><code>data</code>: The callback data passed into <code>method</code>, <code>getter</code> and <code>setter</code> if this
3478function is invoked.</li>
3479</ul>
3480<h4>Functions<span><a class="mark" href="#n_api_functions" id="n_api_functions">#</a></span></h4>
3481<h5>napi_get_property_names<span><a class="mark" href="#n_api_napi_get_property_names" id="n_api_napi_get_property_names">#</a></span></h5>
3482<div class="api_metadata">
3483<span>Added in: v8.0.0</span>
3484<span>N-API version: 1</span>
3485</div>
3486<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_property_names</span><span class="hljs-params">(napi_env env,
3487                                    napi_value object,
3488                                    napi_value* result)</span>;</code></pre>
3489<ul>
3490<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3491<li><code>[in] object</code>: The object from which to retrieve the properties.</li>
3492<li><code>[out] result</code>: A <code>napi_value</code> representing an array of JavaScript values
3493that represent the property names of the object. The API can be used to
3494iterate over <code>result</code> using <a href="#n_api_napi_get_array_length"><code>napi_get_array_length</code></a>
3495and <a href="#n_api_napi_get_element"><code>napi_get_element</code></a>.</li>
3496</ul>
3497<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3498<p>This API returns the names of the enumerable properties of <code>object</code> as an array
3499of strings. The properties of <code>object</code> whose key is a symbol will not be
3500included.</p>
3501<h5>napi_get_all_property_names<span><a class="mark" href="#n_api_napi_get_all_property_names" id="n_api_napi_get_all_property_names">#</a></span></h5>
3502<div class="api_metadata">
3503<span>Added in: v13.7.0, v10.20.0</span>
3504<span>N-API version: 6</span>
3505</div>
3506<pre><code class="language-c">napi_get_all_property_names(napi_env env,
3507                            napi_value object,
3508                            napi_key_collection_mode key_mode,
3509                            napi_key_filter key_filter,
3510                            napi_key_conversion key_conversion,
3511                            napi_value* result);</code></pre>
3512<ul>
3513<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3514<li><code>[in] object</code>: The object from which to retrieve the properties.</li>
3515<li><code>[in] key_mode</code>: Whether to retrieve prototype properties as well.</li>
3516<li><code>[in] key_filter</code>: Which properties to retrieve
3517(enumerable/readable/writable).</li>
3518<li><code>[in] key_conversion</code>: Whether to convert numbered property keys to strings.</li>
3519<li><code>[out] result</code>: A <code>napi_value</code> representing an array of JavaScript values
3520that represent the property names of the object. <a href="#n_api_napi_get_array_length"><code>napi_get_array_length</code></a>
3521and <a href="#n_api_napi_get_element"><code>napi_get_element</code></a> can be used to iterate over <code>result</code>.</li>
3522</ul>
3523<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3524<p>This API returns an array containing the names of the available properties
3525of this object.</p>
3526<h5>napi_set_property<span><a class="mark" href="#n_api_napi_set_property" id="n_api_napi_set_property">#</a></span></h5>
3527<div class="api_metadata">
3528<span>Added in: v8.0.0</span>
3529<span>N-API version: 1</span>
3530</div>
3531<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_set_property</span><span class="hljs-params">(napi_env env,
3532                              napi_value object,
3533                              napi_value key,
3534                              napi_value value)</span>;</code></pre>
3535<ul>
3536<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3537<li><code>[in] object</code>: The object on which to set the property.</li>
3538<li><code>[in] key</code>: The name of the property to set.</li>
3539<li><code>[in] value</code>: The property value.</li>
3540</ul>
3541<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3542<p>This API set a property on the <code>Object</code> passed in.</p>
3543<h5>napi_get_property<span><a class="mark" href="#n_api_napi_get_property" id="n_api_napi_get_property">#</a></span></h5>
3544<div class="api_metadata">
3545<span>Added in: v8.0.0</span>
3546<span>N-API version: 1</span>
3547</div>
3548<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_property</span><span class="hljs-params">(napi_env env,
3549                              napi_value object,
3550                              napi_value key,
3551                              napi_value* result)</span>;</code></pre>
3552<ul>
3553<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3554<li><code>[in] object</code>: The object from which to retrieve the property.</li>
3555<li><code>[in] key</code>: The name of the property to retrieve.</li>
3556<li><code>[out] result</code>: The value of the property.</li>
3557</ul>
3558<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3559<p>This API gets the requested property from the <code>Object</code> passed in.</p>
3560<h5>napi_has_property<span><a class="mark" href="#n_api_napi_has_property" id="n_api_napi_has_property">#</a></span></h5>
3561<div class="api_metadata">
3562<span>Added in: v8.0.0</span>
3563<span>N-API version: 1</span>
3564</div>
3565<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_has_property</span><span class="hljs-params">(napi_env env,
3566                              napi_value object,
3567                              napi_value key,
3568                              <span class="hljs-type">bool</span>* result)</span>;</code></pre>
3569<ul>
3570<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3571<li><code>[in] object</code>: The object to query.</li>
3572<li><code>[in] key</code>: The name of the property whose existence to check.</li>
3573<li><code>[out] result</code>: Whether the property exists on the object or not.</li>
3574</ul>
3575<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3576<p>This API checks if the <code>Object</code> passed in has the named property.</p>
3577<h5>napi_delete_property<span><a class="mark" href="#n_api_napi_delete_property" id="n_api_napi_delete_property">#</a></span></h5>
3578<div class="api_metadata">
3579<span>Added in: v8.2.0</span>
3580<span>N-API version: 1</span>
3581</div>
3582<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_delete_property</span><span class="hljs-params">(napi_env env,
3583                                 napi_value object,
3584                                 napi_value key,
3585                                 <span class="hljs-type">bool</span>* result)</span>;</code></pre>
3586<ul>
3587<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3588<li><code>[in] object</code>: The object to query.</li>
3589<li><code>[in] key</code>: The name of the property to delete.</li>
3590<li><code>[out] result</code>: Whether the property deletion succeeded or not. <code>result</code> can
3591optionally be ignored by passing <code>NULL</code>.</li>
3592</ul>
3593<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3594<p>This API attempts to delete the <code>key</code> own property from <code>object</code>.</p>
3595<h5>napi_has_own_property<span><a class="mark" href="#n_api_napi_has_own_property" id="n_api_napi_has_own_property">#</a></span></h5>
3596<div class="api_metadata">
3597<span>Added in: v8.2.0</span>
3598<span>N-API version: 1</span>
3599</div>
3600<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_has_own_property</span><span class="hljs-params">(napi_env env,
3601                                  napi_value object,
3602                                  napi_value key,
3603                                  <span class="hljs-type">bool</span>* result)</span>;</code></pre>
3604<ul>
3605<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3606<li><code>[in] object</code>: The object to query.</li>
3607<li><code>[in] key</code>: The name of the own property whose existence to check.</li>
3608<li><code>[out] result</code>: Whether the own property exists on the object or not.</li>
3609</ul>
3610<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3611<p>This API checks if the <code>Object</code> passed in has the named own property. <code>key</code> must
3612be a <code>string</code> or a <code>symbol</code>, or an error will be thrown. Node-API will not
3613perform any conversion between data types.</p>
3614<h5>napi_set_named_property<span><a class="mark" href="#n_api_napi_set_named_property" id="n_api_napi_set_named_property">#</a></span></h5>
3615<div class="api_metadata">
3616<span>Added in: v8.0.0</span>
3617<span>N-API version: 1</span>
3618</div>
3619<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_set_named_property</span><span class="hljs-params">(napi_env env,
3620                                    napi_value object,
3621                                    <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* utf8Name,
3622                                    napi_value value)</span>;</code></pre>
3623<ul>
3624<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3625<li><code>[in] object</code>: The object on which to set the property.</li>
3626<li><code>[in] utf8Name</code>: The name of the property to set.</li>
3627<li><code>[in] value</code>: The property value.</li>
3628</ul>
3629<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3630<p>This method is equivalent to calling <a href="#n_api_napi_set_property"><code>napi_set_property</code></a> with a <code>napi_value</code>
3631created from the string passed in as <code>utf8Name</code>.</p>
3632<h5>napi_get_named_property<span><a class="mark" href="#n_api_napi_get_named_property" id="n_api_napi_get_named_property">#</a></span></h5>
3633<div class="api_metadata">
3634<span>Added in: v8.0.0</span>
3635<span>N-API version: 1</span>
3636</div>
3637<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_named_property</span><span class="hljs-params">(napi_env env,
3638                                    napi_value object,
3639                                    <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* utf8Name,
3640                                    napi_value* result)</span>;</code></pre>
3641<ul>
3642<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3643<li><code>[in] object</code>: The object from which to retrieve the property.</li>
3644<li><code>[in] utf8Name</code>: The name of the property to get.</li>
3645<li><code>[out] result</code>: The value of the property.</li>
3646</ul>
3647<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3648<p>This method is equivalent to calling <a href="#n_api_napi_get_property"><code>napi_get_property</code></a> with a <code>napi_value</code>
3649created from the string passed in as <code>utf8Name</code>.</p>
3650<h5>napi_has_named_property<span><a class="mark" href="#n_api_napi_has_named_property" id="n_api_napi_has_named_property">#</a></span></h5>
3651<div class="api_metadata">
3652<span>Added in: v8.0.0</span>
3653<span>N-API version: 1</span>
3654</div>
3655<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_has_named_property</span><span class="hljs-params">(napi_env env,
3656                                    napi_value object,
3657                                    <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* utf8Name,
3658                                    <span class="hljs-type">bool</span>* result)</span>;</code></pre>
3659<ul>
3660<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3661<li><code>[in] object</code>: The object to query.</li>
3662<li><code>[in] utf8Name</code>: The name of the property whose existence to check.</li>
3663<li><code>[out] result</code>: Whether the property exists on the object or not.</li>
3664</ul>
3665<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3666<p>This method is equivalent to calling <a href="#n_api_napi_has_property"><code>napi_has_property</code></a> with a <code>napi_value</code>
3667created from the string passed in as <code>utf8Name</code>.</p>
3668<h5>napi_set_element<span><a class="mark" href="#n_api_napi_set_element" id="n_api_napi_set_element">#</a></span></h5>
3669<div class="api_metadata">
3670<span>Added in: v8.0.0</span>
3671<span>N-API version: 1</span>
3672</div>
3673<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_set_element</span><span class="hljs-params">(napi_env env,
3674                             napi_value object,
3675                             <span class="hljs-type">uint32_t</span> index,
3676                             napi_value value)</span>;</code></pre>
3677<ul>
3678<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3679<li><code>[in] object</code>: The object from which to set the properties.</li>
3680<li><code>[in] index</code>: The index of the property to set.</li>
3681<li><code>[in] value</code>: The property value.</li>
3682</ul>
3683<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3684<p>This API sets and element on the <code>Object</code> passed in.</p>
3685<h5>napi_get_element<span><a class="mark" href="#n_api_napi_get_element" id="n_api_napi_get_element">#</a></span></h5>
3686<div class="api_metadata">
3687<span>Added in: v8.0.0</span>
3688<span>N-API version: 1</span>
3689</div>
3690<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_element</span><span class="hljs-params">(napi_env env,
3691                             napi_value object,
3692                             <span class="hljs-type">uint32_t</span> index,
3693                             napi_value* result)</span>;</code></pre>
3694<ul>
3695<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3696<li><code>[in] object</code>: The object from which to retrieve the property.</li>
3697<li><code>[in] index</code>: The index of the property to get.</li>
3698<li><code>[out] result</code>: The value of the property.</li>
3699</ul>
3700<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3701<p>This API gets the element at the requested index.</p>
3702<h5>napi_has_element<span><a class="mark" href="#n_api_napi_has_element" id="n_api_napi_has_element">#</a></span></h5>
3703<div class="api_metadata">
3704<span>Added in: v8.0.0</span>
3705<span>N-API version: 1</span>
3706</div>
3707<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_has_element</span><span class="hljs-params">(napi_env env,
3708                             napi_value object,
3709                             <span class="hljs-type">uint32_t</span> index,
3710                             <span class="hljs-type">bool</span>* result)</span>;</code></pre>
3711<ul>
3712<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3713<li><code>[in] object</code>: The object to query.</li>
3714<li><code>[in] index</code>: The index of the property whose existence to check.</li>
3715<li><code>[out] result</code>: Whether the property exists on the object or not.</li>
3716</ul>
3717<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3718<p>This API returns if the <code>Object</code> passed in has an element at the
3719requested index.</p>
3720<h5>napi_delete_element<span><a class="mark" href="#n_api_napi_delete_element" id="n_api_napi_delete_element">#</a></span></h5>
3721<div class="api_metadata">
3722<span>Added in: v8.2.0</span>
3723<span>N-API version: 1</span>
3724</div>
3725<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_delete_element</span><span class="hljs-params">(napi_env env,
3726                                napi_value object,
3727                                <span class="hljs-type">uint32_t</span> index,
3728                                <span class="hljs-type">bool</span>* result)</span>;</code></pre>
3729<ul>
3730<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3731<li><code>[in] object</code>: The object to query.</li>
3732<li><code>[in] index</code>: The index of the property to delete.</li>
3733<li><code>[out] result</code>: Whether the element deletion succeeded or not. <code>result</code> can
3734optionally be ignored by passing <code>NULL</code>.</li>
3735</ul>
3736<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3737<p>This API attempts to delete the specified <code>index</code> from <code>object</code>.</p>
3738<h5>napi_define_properties<span><a class="mark" href="#n_api_napi_define_properties" id="n_api_napi_define_properties">#</a></span></h5>
3739<div class="api_metadata">
3740<span>Added in: v8.0.0</span>
3741<span>N-API version: 1</span>
3742</div>
3743<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_define_properties</span><span class="hljs-params">(napi_env env,
3744                                   napi_value object,
3745                                   <span class="hljs-type">size_t</span> property_count,
3746                                   <span class="hljs-keyword">const</span> napi_property_descriptor* properties)</span>;</code></pre>
3747<ul>
3748<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3749<li><code>[in] object</code>: The object from which to retrieve the properties.</li>
3750<li><code>[in] property_count</code>: The number of elements in the <code>properties</code> array.</li>
3751<li><code>[in] properties</code>: The array of property descriptors.</li>
3752</ul>
3753<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3754<p>This method allows the efficient definition of multiple properties on a given
3755object. The properties are defined using property descriptors (see
3756<a href="#n_api_napi_property_descriptor"><code>napi_property_descriptor</code></a>). Given an array of such property descriptors,
3757this API will set the properties on the object one at a time, as defined by
3758<code>DefineOwnProperty()</code> (described in <a href="https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc">Section 9.1.6</a> of the ECMA-262
3759specification).</p>
3760<h5>napi_object_freeze<span><a class="mark" href="#n_api_napi_object_freeze" id="n_api_napi_object_freeze">#</a></span></h5>
3761<div class="api_metadata">
3762<span>Added in: v14.14.0, v12.20.0</span>
3763<span>N-API version: 8</span>
3764</div>
3765<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_object_freeze</span><span class="hljs-params">(napi_env env,
3766                               napi_value object)</span>;</code></pre>
3767<ul>
3768<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3769<li><code>[in] object</code>: The object to freeze.</li>
3770</ul>
3771<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3772<p>This method freezes a given object. This prevents new properties from
3773being added to it, existing properties from being removed, prevents
3774changing the enumerability, configurability, or writability of existing
3775properties, and prevents the values of existing properties from being changed.
3776It also prevents the object's prototype from being changed. This is described
3777in <a href="https://tc39.es/ecma262/#sec-object.freeze">Section 19.1.2.6</a> of the
3778ECMA-262 specification.</p>
3779<h5>napi_object_seal<span><a class="mark" href="#n_api_napi_object_seal" id="n_api_napi_object_seal">#</a></span></h5>
3780<div class="api_metadata">
3781<span>Added in: v14.14.0, v12.20.0</span>
3782<span>N-API version: 8</span>
3783</div>
3784<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_object_seal</span><span class="hljs-params">(napi_env env,
3785                             napi_value object)</span>;</code></pre>
3786<ul>
3787<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
3788<li><code>[in] object</code>: The object to seal.</li>
3789</ul>
3790<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3791<p>This method seals a given object. This prevents new properties from being
3792added to it, as well as marking all existing properties as non-configurable.
3793This is described in <a href="https://tc39.es/ecma262/#sec-object.seal">Section 19.1.2.20</a>
3794of the ECMA-262 specification.</p>
3795</section><section><h3>Working with JavaScript functions<span><a class="mark" href="#n_api_working_with_javascript_functions" id="n_api_working_with_javascript_functions">#</a></span></h3>
3796<p>Node-API provides a set of APIs that allow JavaScript code to
3797call back into native code. Node-APIs that support calling back
3798into native code take in a callback functions represented by
3799the <code>napi_callback</code> type. When the JavaScript VM calls back to
3800native code, the <code>napi_callback</code> function provided is invoked. The APIs
3801documented in this section allow the callback function to do the
3802following:</p>
3803<ul>
3804<li>Get information about the context in which the callback was invoked.</li>
3805<li>Get the arguments passed into the callback.</li>
3806<li>Return a <code>napi_value</code> back from the callback.</li>
3807</ul>
3808<p>Additionally, Node-API provides a set of functions which allow calling
3809JavaScript functions from native code. One can either call a function
3810like a regular JavaScript function call, or as a constructor
3811function.</p>
3812<p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> field of the
3813<code>napi_property_descriptor</code> items can be associated with <code>object</code> and freed
3814whenever <code>object</code> is garbage-collected by passing both <code>object</code> and the data to
3815<a href="#n_api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
3816<h4>napi_call_function<span><a class="mark" href="#n_api_napi_call_function" id="n_api_napi_call_function">#</a></span></h4>
3817<div class="api_metadata">
3818<span>Added in: v8.0.0</span>
3819<span>N-API version: 1</span>
3820</div>
3821<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_call_function</span><span class="hljs-params">(napi_env env,
3822                                           napi_value recv,
3823                                           napi_value func,
3824                                           <span class="hljs-type">size_t</span> argc,
3825                                           <span class="hljs-keyword">const</span> napi_value* argv,
3826                                           napi_value* result)</span>;</code></pre>
3827<ul>
3828<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3829<li><code>[in] recv</code>: The <code>this</code> value passed to the called function.</li>
3830<li><code>[in] func</code>: <code>napi_value</code> representing the JavaScript function to be invoked.</li>
3831<li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li>
3832<li><code>[in] argv</code>: Array of <code>napi_values</code> representing JavaScript values passed in
3833as arguments to the function.</li>
3834<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned.</li>
3835</ul>
3836<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3837<p>This method allows a JavaScript function object to be called from a native
3838add-on. This is the primary mechanism of calling back <em>from</em> the add-on's
3839native code <em>into</em> JavaScript. For the special case of calling into JavaScript
3840after an async operation, see <a href="#n_api_napi_make_callback"><code>napi_make_callback</code></a>.</p>
3841<p>A sample use case might look as follows. Consider the following JavaScript
3842snippet:</p>
3843<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">AddTwo</span>(<span class="hljs-params">num</span>) {
3844  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
3845}</code></pre>
3846<p>Then, the above function can be invoked from a native add-on using the
3847following code:</p>
3848<pre><code class="language-c"><span class="hljs-comment">// Get the function named "AddTwo" on the global object</span>
3849napi_value global, add_two, arg;
3850napi_status status = napi_get_global(env, &#x26;global);
3851<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
3852
3853status = napi_get_named_property(env, global, <span class="hljs-string">"AddTwo"</span>, &#x26;add_two);
3854<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
3855
3856<span class="hljs-comment">// const arg = 1337</span>
3857status = napi_create_int32(env, <span class="hljs-number">1337</span>, &#x26;arg);
3858<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
3859
3860napi_value* argv = &#x26;arg;
3861<span class="hljs-type">size_t</span> argc = <span class="hljs-number">1</span>;
3862
3863<span class="hljs-comment">// AddTwo(arg);</span>
3864napi_value return_val;
3865status = napi_call_function(env, global, add_two, argc, argv, &#x26;return_val);
3866<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
3867
3868<span class="hljs-comment">// Convert the result back to a native type</span>
3869<span class="hljs-type">int32_t</span> result;
3870status = napi_get_value_int32(env, return_val, &#x26;result);
3871<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;</code></pre>
3872<h4>napi_create_function<span><a class="mark" href="#n_api_napi_create_function" id="n_api_napi_create_function">#</a></span></h4>
3873<div class="api_metadata">
3874<span>Added in: v8.0.0</span>
3875<span>N-API version: 1</span>
3876</div>
3877<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_function</span><span class="hljs-params">(napi_env env,
3878                                 <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* utf8name,
3879                                 <span class="hljs-type">size_t</span> length,
3880                                 napi_callback cb,
3881                                 <span class="hljs-type">void</span>* data,
3882                                 napi_value* result)</span>;</code></pre>
3883<ul>
3884<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3885<li><code>[in] utf8Name</code>: The name of the function encoded as UTF8. This is visible
3886within JavaScript as the new function object's <code>name</code> property.</li>
3887<li><code>[in] length</code>: The length of the <code>utf8name</code> in bytes, or <code>NAPI_AUTO_LENGTH</code> if
3888it is null-terminated.</li>
3889<li><code>[in] cb</code>: The native function which should be called when this function
3890object is invoked. <a href="#n_api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
3891<li><code>[in] data</code>: User-provided data context. This will be passed back into the
3892function when invoked later.</li>
3893<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript function object for
3894the newly created function.</li>
3895</ul>
3896<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3897<p>This API allows an add-on author to create a function object in native code.
3898This is the primary mechanism to allow calling <em>into</em> the add-on's native code
3899<em>from</em> JavaScript.</p>
3900<p>The newly created function is not automatically visible from script after this
3901call. Instead, a property must be explicitly set on any object that is visible
3902to JavaScript, in order for the function to be accessible from script.</p>
3903<p>In order to expose a function as part of the
3904add-on's module exports, set the newly created function on the exports
3905object. A sample module might look as follows:</p>
3906<pre><code class="language-c">napi_value <span class="hljs-title function_">SayHello</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
3907  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello\n"</span>);
3908  <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
3909}
3910
3911napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
3912  napi_status status;
3913
3914  napi_value fn;
3915  status = napi_create_function(env, <span class="hljs-literal">NULL</span>, <span class="hljs-number">0</span>, SayHello, <span class="hljs-literal">NULL</span>, &#x26;fn);
3916  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
3917
3918  status = napi_set_named_property(env, exports, <span class="hljs-string">"sayHello"</span>, fn);
3919  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
3920
3921  <span class="hljs-keyword">return</span> exports;
3922}
3923
3924NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)</code></pre>
3925<p>Given the above code, the add-on can be used from JavaScript as follows:</p>
3926<pre><code class="language-js"><span class="hljs-keyword">const</span> myaddon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./addon'</span>);
3927myaddon.<span class="hljs-title function_">sayHello</span>();</code></pre>
3928<p>The string passed to <code>require()</code> is the name of the target in <code>binding.gyp</code>
3929responsible for creating the <code>.node</code> file.</p>
3930<p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> parameter can
3931be associated with the resulting JavaScript function (which is returned in the
3932<code>result</code> parameter) and freed whenever the function is garbage-collected by
3933passing both the JavaScript function and the data to <a href="#n_api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
3934<p>JavaScript <code>Function</code>s are described in <a href="https://tc39.github.io/ecma262/#sec-function-objects">Section 19.2</a> of the ECMAScript
3935Language Specification.</p>
3936<h4>napi_get_cb_info<span><a class="mark" href="#n_api_napi_get_cb_info" id="n_api_napi_get_cb_info">#</a></span></h4>
3937<div class="api_metadata">
3938<span>Added in: v8.0.0</span>
3939<span>N-API version: 1</span>
3940</div>
3941<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_cb_info</span><span class="hljs-params">(napi_env env,
3942                             napi_callback_info cbinfo,
3943                             <span class="hljs-type">size_t</span>* argc,
3944                             napi_value* argv,
3945                             napi_value* thisArg,
3946                             <span class="hljs-type">void</span>** data)</span></code></pre>
3947<ul>
3948<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3949<li><code>[in] cbinfo</code>: The callback info passed into the callback function.</li>
3950<li><code>[in-out] argc</code>: Specifies the length of the provided <code>argv</code> array and
3951receives the actual count of arguments.</li>
3952<li><code>[out] argv</code>: Buffer to which the <code>napi_value</code> representing the arguments are
3953copied. If there are more arguments than the provided count, only the
3954requested number of arguments are copied. If there are fewer arguments
3955provided than claimed, the rest of <code>argv</code> is filled with <code>napi_value</code> values
3956that represent <code>undefined</code>.</li>
3957<li><code>[out] this</code>: Receives the JavaScript <code>this</code> argument for the call.</li>
3958<li><code>[out] data</code>: Receives the data pointer for the callback.</li>
3959</ul>
3960<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3961<p>This method is used within a callback function to retrieve details about the
3962call like the arguments and the <code>this</code> pointer from a given callback info.</p>
3963<h4>napi_get_new_target<span><a class="mark" href="#n_api_napi_get_new_target" id="n_api_napi_get_new_target">#</a></span></h4>
3964<div class="api_metadata">
3965<span>Added in: v8.6.0</span>
3966<span>N-API version: 1</span>
3967</div>
3968<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_new_target</span><span class="hljs-params">(napi_env env,
3969                                napi_callback_info cbinfo,
3970                                napi_value* result)</span></code></pre>
3971<ul>
3972<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3973<li><code>[in] cbinfo</code>: The callback info passed into the callback function.</li>
3974<li><code>[out] result</code>: The <code>new.target</code> of the constructor call.</li>
3975</ul>
3976<p>Returns <code>napi_ok</code> if the API succeeded.</p>
3977<p>This API returns the <code>new.target</code> of the constructor call. If the current
3978callback is not a constructor call, the result is <code>NULL</code>.</p>
3979<h4>napi_new_instance<span><a class="mark" href="#n_api_napi_new_instance" id="n_api_napi_new_instance">#</a></span></h4>
3980<div class="api_metadata">
3981<span>Added in: v8.0.0</span>
3982<span>N-API version: 1</span>
3983</div>
3984<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_new_instance</span><span class="hljs-params">(napi_env env,
3985                              napi_value cons,
3986                              <span class="hljs-type">size_t</span> argc,
3987                              napi_value* argv,
3988                              napi_value* result)</span></code></pre>
3989<ul>
3990<li><code>[in] env</code>: The environment that the API is invoked under.</li>
3991<li><code>[in] cons</code>: <code>napi_value</code> representing the JavaScript function to be invoked
3992as a constructor.</li>
3993<li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li>
3994<li><code>[in] argv</code>: Array of JavaScript values as <code>napi_value</code> representing the
3995arguments to the constructor.</li>
3996<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned,
3997which in this case is the constructed object.</li>
3998</ul>
3999<p>This method is used to instantiate a new JavaScript value using a given
4000<code>napi_value</code> that represents the constructor for the object. For example,
4001consider the following snippet:</p>
4002<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">MyObject</span>(<span class="hljs-params">param</span>) {
4003  <span class="hljs-variable language_">this</span>.<span class="hljs-property">param</span> = param;
4004}
4005
4006<span class="hljs-keyword">const</span> arg = <span class="hljs-string">'hello'</span>;
4007<span class="hljs-keyword">const</span> value = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyObject</span>(arg);</code></pre>
4008<p>The following can be approximated in Node-API using the following snippet:</p>
4009<pre><code class="language-c"><span class="hljs-comment">// Get the constructor function MyObject</span>
4010napi_value global, constructor, arg, value;
4011napi_status status = napi_get_global(env, &#x26;global);
4012<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
4013
4014status = napi_get_named_property(env, global, <span class="hljs-string">"MyObject"</span>, &#x26;constructor);
4015<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
4016
4017<span class="hljs-comment">// const arg = "hello"</span>
4018status = napi_create_string_utf8(env, <span class="hljs-string">"hello"</span>, NAPI_AUTO_LENGTH, &#x26;arg);
4019<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
4020
4021napi_value* argv = &#x26;arg;
4022<span class="hljs-type">size_t</span> argc = <span class="hljs-number">1</span>;
4023
4024<span class="hljs-comment">// const value = new MyObject(arg)</span>
4025status = napi_new_instance(env, constructor, argc, argv, &#x26;value);</code></pre>
4026<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4027</section><section><h3>Object wrap<span><a class="mark" href="#n_api_object_wrap" id="n_api_object_wrap">#</a></span></h3>
4028<p>Node-API offers a way to "wrap" C++ classes and instances so that the class
4029constructor and methods can be called from JavaScript.</p>
4030<ol>
4031<li>The <a href="#n_api_napi_define_class"><code>napi_define_class</code></a> API defines a JavaScript class with constructor,
4032static properties and methods, and instance properties and methods that
4033correspond to the C++ class.</li>
4034<li>When JavaScript code invokes the constructor, the constructor callback
4035uses <a href="#n_api_napi_wrap"><code>napi_wrap</code></a> to wrap a new C++ instance in a JavaScript object,
4036then returns the wrapper object.</li>
4037<li>When JavaScript code invokes a method or property accessor on the class,
4038the corresponding <code>napi_callback</code> C++ function is invoked. For an instance
4039callback, <a href="#n_api_napi_unwrap"><code>napi_unwrap</code></a> obtains the C++ instance that is the target of
4040the call.</li>
4041</ol>
4042<p>For wrapped objects it may be difficult to distinguish between a function
4043called on a class prototype and a function called on an instance of a class.
4044A common pattern used to address this problem is to save a persistent
4045reference to the class constructor for later <code>instanceof</code> checks.</p>
4046<pre><code class="language-c">napi_value MyClass_constructor = <span class="hljs-literal">NULL</span>;
4047status = napi_get_reference_value(env, MyClass::es_constructor, &#x26;MyClass_constructor);
4048assert(napi_ok == status);
4049<span class="hljs-type">bool</span> is_instance = <span class="hljs-literal">false</span>;
4050status = napi_instanceof(env, es_this, MyClass_constructor, &#x26;is_instance);
4051assert(napi_ok == status);
4052<span class="hljs-keyword">if</span> (is_instance) {
4053  <span class="hljs-comment">// napi_unwrap() ...</span>
4054} <span class="hljs-keyword">else</span> {
4055  <span class="hljs-comment">// otherwise...</span>
4056}</code></pre>
4057<p>The reference must be freed once it is no longer needed.</p>
4058<p>There are occasions where <code>napi_instanceof()</code> is insufficient for ensuring that
4059a JavaScript object is a wrapper for a certain native type. This is the case
4060especially when wrapped JavaScript objects are passed back into the addon via
4061static methods rather than as the <code>this</code> value of prototype methods. In such
4062cases there is a chance that they may be unwrapped incorrectly.</p>
4063<pre><code class="language-js"><span class="hljs-keyword">const</span> myAddon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/my_addon.node'</span>);
4064
4065<span class="hljs-comment">// `openDatabase()` returns a JavaScript object that wraps a native database</span>
4066<span class="hljs-comment">// handle.</span>
4067<span class="hljs-keyword">const</span> dbHandle = myAddon.<span class="hljs-title function_">openDatabase</span>();
4068
4069<span class="hljs-comment">// `query()` returns a JavaScript object that wraps a native query handle.</span>
4070<span class="hljs-keyword">const</span> queryHandle = myAddon.<span class="hljs-title function_">query</span>(dbHandle, <span class="hljs-string">'Gimme ALL the things!'</span>);
4071
4072<span class="hljs-comment">// There is an accidental error in the line below. The first parameter to</span>
4073<span class="hljs-comment">// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not</span>
4074<span class="hljs-comment">// the query handle (`query`), so the correct condition for the while-loop</span>
4075<span class="hljs-comment">// should be</span>
4076<span class="hljs-comment">//</span>
4077<span class="hljs-comment">// myAddon.queryHasRecords(dbHandle, queryHandle)</span>
4078<span class="hljs-comment">//</span>
4079<span class="hljs-keyword">while</span> (myAddon.<span class="hljs-title function_">queryHasRecords</span>(queryHandle, dbHandle)) {
4080  <span class="hljs-comment">// retrieve records</span>
4081}</code></pre>
4082<p>In the above example <code>myAddon.queryHasRecords()</code> is a method that accepts two
4083arguments. The first is a database handle and the second is a query handle.
4084Internally, it unwraps the first argument and casts the resulting pointer to a
4085native database handle. It then unwraps the second argument and casts the
4086resulting pointer to a query handle. If the arguments are passed in the wrong
4087order, the casts will work, however, there is a good chance that the underlying
4088database operation will fail, or will even cause an invalid memory access.</p>
4089<p>To ensure that the pointer retrieved from the first argument is indeed a pointer
4090to a database handle and, similarly, that the pointer retrieved from the second
4091argument is indeed a pointer to a query handle, the implementation of
4092<code>queryHasRecords()</code> has to perform a type validation. Retaining the JavaScript
4093class constructor from which the database handle was instantiated and the
4094constructor from which the query handle was instantiated in <code>napi_ref</code>s can
4095help, because <code>napi_instanceof()</code> can then be used to ensure that the instances
4096passed into <code>queryHashRecords()</code> are indeed of the correct type.</p>
4097<p>Unfortunately, <code>napi_instanceof()</code> does not protect against prototype
4098manipulation. For example, the prototype of the database handle instance can be
4099set to the prototype of the constructor for query handle instances. In this
4100case, the database handle instance can appear as a query handle instance, and it
4101will pass the <code>napi_instanceof()</code> test for a query handle instance, while still
4102containing a pointer to a database handle.</p>
4103<p>To this end, Node-API provides type-tagging capabilities.</p>
4104<p>A type tag is a 128-bit integer unique to the addon. Node-API provides the
4105<code>napi_type_tag</code> structure for storing a type tag. When such a value is passed
4106along with a JavaScript object stored in a <code>napi_value</code> to
4107<code>napi_type_tag_object()</code>, the JavaScript object will be "marked" with the
4108type tag. The "mark" is invisible on the JavaScript side. When a JavaScript
4109object arrives into a native binding, <code>napi_check_object_type_tag()</code> can be used
4110along with the original type tag to determine whether the JavaScript object was
4111previously "marked" with the type tag. This creates a type-checking capability
4112of a higher fidelity than <code>napi_instanceof()</code> can provide, because such type-
4113tagging survives prototype manipulation and addon unloading/reloading.</p>
4114<p>Continuing the above example, the following skeleton addon implementation
4115illustrates the use of <code>napi_type_tag_object()</code> and
4116<code>napi_check_object_type_tag()</code>.</p>
4117<pre><code class="language-c"><span class="hljs-comment">// This value is the type tag for a database handle. The command</span>
4118<span class="hljs-comment">//</span>
4119<span class="hljs-comment">//   uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\1, 0x\2/'</span>
4120<span class="hljs-comment">//</span>
4121<span class="hljs-comment">// can be used to obtain the two values with which to initialize the structure.</span>
4122<span class="hljs-keyword">static</span> <span class="hljs-keyword">const</span> napi_type_tag DatabaseHandleTypeTag = {
4123  <span class="hljs-number">0x1edf75a38336451d</span>, <span class="hljs-number">0xa5ed9ce2e4c00c38</span>
4124};
4125
4126<span class="hljs-comment">// This value is the type tag for a query handle.</span>
4127<span class="hljs-keyword">static</span> <span class="hljs-keyword">const</span> napi_type_tag QueryHandleTypeTag = {
4128  <span class="hljs-number">0x9c73317f9fad44a3</span>, <span class="hljs-number">0x93c3920bf3b0ad6a</span>
4129};
4130
4131<span class="hljs-keyword">static</span> napi_value
4132<span class="hljs-title function_">openDatabase</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
4133  napi_status status;
4134  napi_value result;
4135
4136  <span class="hljs-comment">// Perform the underlying action which results in a database handle.</span>
4137  DatabaseHandle* dbHandle = open_database();
4138
4139  <span class="hljs-comment">// Create a new, empty JS object.</span>
4140  status = napi_create_object(env, &#x26;result);
4141  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
4142
4143  <span class="hljs-comment">// Tag the object to indicate that it holds a pointer to a `DatabaseHandle`.</span>
4144  status = napi_type_tag_object(env, result, &#x26;DatabaseHandleTypeTag);
4145  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
4146
4147  <span class="hljs-comment">// Store the pointer to the `DatabaseHandle` structure inside the JS object.</span>
4148  status = napi_wrap(env, result, dbHandle, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>);
4149  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
4150
4151  <span class="hljs-keyword">return</span> result;
4152}
4153
4154<span class="hljs-comment">// Later when we receive a JavaScript object purporting to be a database handle</span>
4155<span class="hljs-comment">// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a</span>
4156<span class="hljs-comment">// handle.</span>
4157
4158<span class="hljs-keyword">static</span> napi_value
4159<span class="hljs-title function_">query</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
4160  napi_status status;
4161  <span class="hljs-type">size_t</span> argc = <span class="hljs-number">2</span>;
4162  napi_value argv[<span class="hljs-number">2</span>];
4163  <span class="hljs-type">bool</span> is_db_handle;
4164
4165  status = napi_get_cb_info(env, info, &#x26;argc, argv, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>);
4166  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
4167
4168  <span class="hljs-comment">// Check that the object passed as the first parameter has the previously</span>
4169  <span class="hljs-comment">// applied tag.</span>
4170  status = napi_check_object_type_tag(env,
4171                                      argv[<span class="hljs-number">0</span>],
4172                                      &#x26;DatabaseHandleTypeTag,
4173                                      &#x26;is_db_handle);
4174  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
4175
4176  <span class="hljs-comment">// Throw a `TypeError` if it doesn't.</span>
4177  <span class="hljs-keyword">if</span> (!is_db_handle) {
4178    <span class="hljs-comment">// Throw a TypeError.</span>
4179    <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
4180  }
4181}</code></pre>
4182<h4>napi_define_class<span><a class="mark" href="#n_api_napi_define_class" id="n_api_napi_define_class">#</a></span></h4>
4183<div class="api_metadata">
4184<span>Added in: v8.0.0</span>
4185<span>N-API version: 1</span>
4186</div>
4187<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_define_class</span><span class="hljs-params">(napi_env env,
4188                              <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* utf8name,
4189                              <span class="hljs-type">size_t</span> length,
4190                              napi_callback constructor,
4191                              <span class="hljs-type">void</span>* data,
4192                              <span class="hljs-type">size_t</span> property_count,
4193                              <span class="hljs-keyword">const</span> napi_property_descriptor* properties,
4194                              napi_value* result)</span>;</code></pre>
4195<ul>
4196<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4197<li><code>[in] utf8name</code>: Name of the JavaScript constructor function; When wrapping a
4198C++ class, we recommend for clarity that this name be the same as that of
4199the C++ class.</li>
4200<li><code>[in] length</code>: The length of the <code>utf8name</code> in bytes, or <code>NAPI_AUTO_LENGTH</code>
4201if it is null-terminated.</li>
4202<li><code>[in] constructor</code>: Callback function that handles constructing instances
4203of the class. When wrapping a C++ class, this method must be a static member
4204with the <a href="#n_api_napi_callback"><code>napi_callback</code></a> signature. A C++ class constructor cannot be
4205used. <a href="#n_api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
4206<li><code>[in] data</code>: Optional data to be passed to the constructor callback as
4207the <code>data</code> property of the callback info.</li>
4208<li><code>[in] property_count</code>: Number of items in the <code>properties</code> array argument.</li>
4209<li><code>[in] properties</code>: Array of property descriptors describing static and
4210instance data properties, accessors, and methods on the class
4211See <code>napi_property_descriptor</code>.</li>
4212<li><code>[out] result</code>: A <code>napi_value</code> representing the constructor function for
4213the class.</li>
4214</ul>
4215<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4216<p>Defines a JavaScript class, including:</p>
4217<ul>
4218<li>A JavaScript constructor function that has the class name. When wrapping a
4219corresponding C++ class, the callback passed via <code>constructor</code> can be used to
4220instantiate a new C++ class instance, which can then be placed inside the
4221JavaScript object instance being constructed using <a href="#n_api_napi_wrap"><code>napi_wrap</code></a>.</li>
4222<li>Properties on the constructor function whose implementation can call
4223corresponding <em>static</em> data properties, accessors, and methods of the C++
4224class (defined by property descriptors with the <code>napi_static</code> attribute).</li>
4225<li>Properties on the constructor function's <code>prototype</code> object. When wrapping a
4226C++ class, <em>non-static</em> data properties, accessors, and methods of the C++
4227class can be called from the static functions given in the property
4228descriptors without the <code>napi_static</code> attribute after retrieving the C++ class
4229instance placed inside the JavaScript object instance by using
4230<a href="#n_api_napi_unwrap"><code>napi_unwrap</code></a>.</li>
4231</ul>
4232<p>When wrapping a C++ class, the C++ constructor callback passed via <code>constructor</code>
4233should be a static method on the class that calls the actual class constructor,
4234then wraps the new C++ instance in a JavaScript object, and returns the wrapper
4235object. See <a href="#n_api_napi_wrap"><code>napi_wrap</code></a> for details.</p>
4236<p>The JavaScript constructor function returned from <a href="#n_api_napi_define_class"><code>napi_define_class</code></a> is
4237often saved and used later to construct new instances of the class from native
4238code, and/or to check whether provided values are instances of the class. In
4239that case, to prevent the function value from being garbage-collected, a
4240strong persistent reference to it can be created using
4241<a href="#n_api_napi_create_reference"><code>napi_create_reference</code></a>, ensuring that the reference count is kept >= 1.</p>
4242<p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> parameter or via
4243the <code>data</code> field of the <code>napi_property_descriptor</code> array items can be associated
4244with the resulting JavaScript constructor (which is returned in the <code>result</code>
4245parameter) and freed whenever the class is garbage-collected by passing both
4246the JavaScript function and the data to <a href="#n_api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
4247<h4>napi_wrap<span><a class="mark" href="#n_api_napi_wrap" id="n_api_napi_wrap">#</a></span></h4>
4248<div class="api_metadata">
4249<span>Added in: v8.0.0</span>
4250<span>N-API version: 1</span>
4251</div>
4252<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_wrap</span><span class="hljs-params">(napi_env env,
4253                      napi_value js_object,
4254                      <span class="hljs-type">void</span>* native_object,
4255                      napi_finalize finalize_cb,
4256                      <span class="hljs-type">void</span>* finalize_hint,
4257                      napi_ref* result)</span>;</code></pre>
4258<ul>
4259<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4260<li><code>[in] js_object</code>: The JavaScript object that will be the wrapper for the
4261native object.</li>
4262<li><code>[in] native_object</code>: The native instance that will be wrapped in the
4263JavaScript object.</li>
4264<li><code>[in] finalize_cb</code>: Optional native callback that can be used to free the
4265native instance when the JavaScript object is ready for garbage-collection.
4266<a href="#n_api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
4267<li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the
4268finalize callback.</li>
4269<li><code>[out] result</code>: Optional reference to the wrapped object.</li>
4270</ul>
4271<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4272<p>Wraps a native instance in a JavaScript object. The native instance can be
4273retrieved later using <code>napi_unwrap()</code>.</p>
4274<p>When JavaScript code invokes a constructor for a class that was defined using
4275<code>napi_define_class()</code>, the <code>napi_callback</code> for the constructor is invoked.
4276After constructing an instance of the native class, the callback must then call
4277<code>napi_wrap()</code> to wrap the newly constructed instance in the already-created
4278JavaScript object that is the <code>this</code> argument to the constructor callback.
4279(That <code>this</code> object was created from the constructor function's <code>prototype</code>,
4280so it already has definitions of all the instance properties and methods.)</p>
4281<p>Typically when wrapping a class instance, a finalize callback should be
4282provided that simply deletes the native instance that is received as the <code>data</code>
4283argument to the finalize callback.</p>
4284<p>The optional returned reference is initially a weak reference, meaning it
4285has a reference count of 0. Typically this reference count would be incremented
4286temporarily during async operations that require the instance to remain valid.</p>
4287<p><em>Caution</em>: The optional returned reference (if obtained) should be deleted via
4288<a href="#n_api_napi_delete_reference"><code>napi_delete_reference</code></a> ONLY in response to the finalize callback
4289invocation. If it is deleted before then, then the finalize callback may never
4290be invoked. Therefore, when obtaining a reference a finalize callback is also
4291required in order to enable correct disposal of the reference.</p>
4292<p>Calling <code>napi_wrap()</code> a second time on an object will return an error. To
4293associate another native instance with the object, use <code>napi_remove_wrap()</code>
4294first.</p>
4295<h4>napi_unwrap<span><a class="mark" href="#n_api_napi_unwrap" id="n_api_napi_unwrap">#</a></span></h4>
4296<div class="api_metadata">
4297<span>Added in: v8.0.0</span>
4298<span>N-API version: 1</span>
4299</div>
4300<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_unwrap</span><span class="hljs-params">(napi_env env,
4301                        napi_value js_object,
4302                        <span class="hljs-type">void</span>** result)</span>;</code></pre>
4303<ul>
4304<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4305<li><code>[in] js_object</code>: The object associated with the native instance.</li>
4306<li><code>[out] result</code>: Pointer to the wrapped native instance.</li>
4307</ul>
4308<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4309<p>Retrieves a native instance that was previously wrapped in a JavaScript
4310object using <code>napi_wrap()</code>.</p>
4311<p>When JavaScript code invokes a method or property accessor on the class, the
4312corresponding <code>napi_callback</code> is invoked. If the callback is for an instance
4313method or accessor, then the <code>this</code> argument to the callback is the wrapper
4314object; the wrapped C++ instance that is the target of the call can be obtained
4315then by calling <code>napi_unwrap()</code> on the wrapper object.</p>
4316<h4>napi_remove_wrap<span><a class="mark" href="#n_api_napi_remove_wrap" id="n_api_napi_remove_wrap">#</a></span></h4>
4317<div class="api_metadata">
4318<span>Added in: v8.5.0</span>
4319<span>N-API version: 1</span>
4320</div>
4321<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_remove_wrap</span><span class="hljs-params">(napi_env env,
4322                             napi_value js_object,
4323                             <span class="hljs-type">void</span>** result)</span>;</code></pre>
4324<ul>
4325<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4326<li><code>[in] js_object</code>: The object associated with the native instance.</li>
4327<li><code>[out] result</code>: Pointer to the wrapped native instance.</li>
4328</ul>
4329<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4330<p>Retrieves a native instance that was previously wrapped in the JavaScript
4331object <code>js_object</code> using <code>napi_wrap()</code> and removes the wrapping. If a finalize
4332callback was associated with the wrapping, it will no longer be called when the
4333JavaScript object becomes garbage-collected.</p>
4334<h4>napi_type_tag_object<span><a class="mark" href="#n_api_napi_type_tag_object" id="n_api_napi_type_tag_object">#</a></span></h4>
4335<div class="api_metadata">
4336<span>Added in: v14.8.0, v12.19.0</span>
4337<span>N-API version: 8</span>
4338</div>
4339<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_type_tag_object</span><span class="hljs-params">(napi_env env,
4340                                 napi_value js_object,
4341                                 <span class="hljs-keyword">const</span> napi_type_tag* type_tag)</span>;</code></pre>
4342<ul>
4343<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4344<li><code>[in] js_object</code>: The JavaScript object to be marked.</li>
4345<li><code>[in] type_tag</code>: The tag with which the object is to be marked.</li>
4346</ul>
4347<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4348<p>Associates the value of the <code>type_tag</code> pointer with the JavaScript object.
4349<code>napi_check_object_type_tag()</code> can then be used to compare the tag that was
4350attached to the object with one owned by the addon to ensure that the object
4351has the right type.</p>
4352<p>If the object already has an associated type tag, this API will return
4353<code>napi_invalid_arg</code>.</p>
4354<h4>napi_check_object_type_tag<span><a class="mark" href="#n_api_napi_check_object_type_tag" id="n_api_napi_check_object_type_tag">#</a></span></h4>
4355<div class="api_metadata">
4356<span>Added in: v14.8.0, v12.19.0</span>
4357<span>N-API version: 8</span>
4358</div>
4359<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_check_object_type_tag</span><span class="hljs-params">(napi_env env,
4360                                       napi_value js_object,
4361                                       <span class="hljs-keyword">const</span> napi_type_tag* type_tag,
4362                                       <span class="hljs-type">bool</span>* result)</span>;</code></pre>
4363<ul>
4364<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4365<li><code>[in] js_object</code>: The JavaScript object whose type tag to examine.</li>
4366<li><code>[in] type_tag</code>: The tag with which to compare any tag found on the object.</li>
4367<li><code>[out] result</code>: Whether the type tag given matched the type tag on the
4368object. <code>false</code> is also returned if no type tag was found on the object.</li>
4369</ul>
4370<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4371<p>Compares the pointer given as <code>type_tag</code> with any that can be found on
4372<code>js_object</code>. If no tag is found on <code>js_object</code> or, if a tag is found but it does
4373not match <code>type_tag</code>, then <code>result</code> is set to <code>false</code>. If a tag is found and it
4374matches <code>type_tag</code>, then <code>result</code> is set to <code>true</code>.</p>
4375<h4>napi_add_finalizer<span><a class="mark" href="#n_api_napi_add_finalizer" id="n_api_napi_add_finalizer">#</a></span></h4>
4376<div class="api_metadata">
4377<span>Added in: v8.0.0</span>
4378<span>N-API version: 5</span>
4379</div>
4380<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_add_finalizer</span><span class="hljs-params">(napi_env env,
4381                               napi_value js_object,
4382                               <span class="hljs-type">void</span>* native_object,
4383                               napi_finalize finalize_cb,
4384                               <span class="hljs-type">void</span>* finalize_hint,
4385                               napi_ref* result)</span>;</code></pre>
4386<ul>
4387<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4388<li><code>[in] js_object</code>: The JavaScript object to which the native data will be
4389attached.</li>
4390<li><code>[in] native_object</code>: The native data that will be attached to the JavaScript
4391object.</li>
4392<li><code>[in] finalize_cb</code>: Native callback that will be used to free the
4393native data when the JavaScript object is ready for garbage-collection.
4394<a href="#n_api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
4395<li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the
4396finalize callback.</li>
4397<li><code>[out] result</code>: Optional reference to the JavaScript object.</li>
4398</ul>
4399<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4400<p>Adds a <code>napi_finalize</code> callback which will be called when the JavaScript object
4401in <code>js_object</code> is ready for garbage collection. This API is similar to
4402<code>napi_wrap()</code> except that:</p>
4403<ul>
4404<li>the native data cannot be retrieved later using <code>napi_unwrap()</code>,</li>
4405<li>nor can it be removed later using <code>napi_remove_wrap()</code>, and</li>
4406<li>the API can be called multiple times with different data items in order to
4407attach each of them to the JavaScript object, and</li>
4408<li>the object manipulated by the API can be used with <code>napi_wrap()</code>.</li>
4409</ul>
4410<p><em>Caution</em>: The optional returned reference (if obtained) should be deleted via
4411<a href="#n_api_napi_delete_reference"><code>napi_delete_reference</code></a> ONLY in response to the finalize callback
4412invocation. If it is deleted before then, then the finalize callback may never
4413be invoked. Therefore, when obtaining a reference a finalize callback is also
4414required in order to enable correct disposal of the reference.</p>
4415</section><section><h3>Simple asynchronous operations<span><a class="mark" href="#n_api_simple_asynchronous_operations" id="n_api_simple_asynchronous_operations">#</a></span></h3>
4416<p>Addon modules often need to leverage async helpers from libuv as part of their
4417implementation. This allows them to schedule work to be executed asynchronously
4418so that their methods can return in advance of the work being completed. This
4419allows them to avoid blocking overall execution of the Node.js application.</p>
4420<p>Node-API provides an ABI-stable interface for these
4421supporting functions which covers the most common asynchronous use cases.</p>
4422<p>Node-API defines the <code>napi_async_work</code> structure which is used to manage
4423asynchronous workers. Instances are created/deleted with
4424<a href="#n_api_napi_create_async_work"><code>napi_create_async_work</code></a> and <a href="#n_api_napi_delete_async_work"><code>napi_delete_async_work</code></a>.</p>
4425<p>The <code>execute</code> and <code>complete</code> callbacks are functions that will be
4426invoked when the executor is ready to execute and when it completes its
4427task respectively.</p>
4428<p>The <code>execute</code> function should avoid making any Node-API calls
4429that could result in the execution of JavaScript or interaction with
4430JavaScript objects. Most often, any code that needs to make Node-API
4431calls should be made in <code>complete</code> callback instead.
4432Avoid using the <code>napi_env</code> parameter in the execute callback as
4433it will likely execute JavaScript.</p>
4434<p>These functions implement the following interfaces:</p>
4435<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_execute_callback)</span><span class="hljs-params">(napi_env env,
4436                                            <span class="hljs-type">void</span>* data)</span>;
4437<span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_complete_callback)</span><span class="hljs-params">(napi_env env,
4438                                             napi_status status,
4439                                             <span class="hljs-type">void</span>* data)</span>;</code></pre>
4440<p>When these methods are invoked, the <code>data</code> parameter passed will be the
4441addon-provided <code>void*</code> data that was passed into the
4442<code>napi_create_async_work</code> call.</p>
4443<p>Once created the async worker can be queued
4444for execution using the <a href="#n_api_napi_queue_async_work"><code>napi_queue_async_work</code></a> function:</p>
4445<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_queue_async_work</span><span class="hljs-params">(napi_env env,
4446                                  napi_async_work work)</span>;</code></pre>
4447<p><a href="#n_api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a> can be used if the work needs
4448to be cancelled before the work has started execution.</p>
4449<p>After calling <a href="#n_api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a>, the <code>complete</code> callback
4450will be invoked with a status value of <code>napi_cancelled</code>.
4451The work should not be deleted before the <code>complete</code>
4452callback invocation, even when it was cancelled.</p>
4453<h4>napi_create_async_work<span><a class="mark" href="#n_api_napi_create_async_work" id="n_api_napi_create_async_work">#</a></span></h4>
4454<div class="api_metadata">
4455<details class="changelog"><summary>History</summary>
4456<table>
4457<tbody><tr><th>Version</th><th>Changes</th></tr>
4458<tr><td>v8.6.0</td>
4459<td><p>Added <code>async_resource</code> and <code>async_resource_name</code> parameters.</p></td></tr>
4460<tr><td>v8.0.0</td>
4461<td><p><span>Added in: v8.0.0</span></p></td></tr>
4462</tbody></table>
4463</details>
4464<span>N-API version: 1</span>
4465</div>
4466<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_async_work</span><span class="hljs-params">(napi_env env,
4467                                   napi_value async_resource,
4468                                   napi_value async_resource_name,
4469                                   napi_async_execute_callback execute,
4470                                   napi_async_complete_callback complete,
4471                                   <span class="hljs-type">void</span>* data,
4472                                   napi_async_work* result)</span>;</code></pre>
4473<ul>
4474<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4475<li><code>[in] async_resource</code>: An optional object associated with the async work
4476that will be passed to possible <code>async_hooks</code> <a href="async_hooks.html#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.</li>
4477<li><code>[in] async_resource_name</code>: Identifier for the kind of resource that is being
4478provided for diagnostic information exposed by the <code>async_hooks</code> API.</li>
4479<li><code>[in] execute</code>: The native function which should be called to execute the
4480logic asynchronously. The given function is called from a worker pool thread
4481and can execute in parallel with the main event loop thread.</li>
4482<li><code>[in] complete</code>: The native function which will be called when the
4483asynchronous logic is completed or is cancelled. The given function is called
4484from the main event loop thread. <a href="#n_api_napi_async_complete_callback"><code>napi_async_complete_callback</code></a> provides
4485more details.</li>
4486<li><code>[in] data</code>: User-provided data context. This will be passed back into the
4487execute and complete functions.</li>
4488<li><code>[out] result</code>: <code>napi_async_work*</code> which is the handle to the newly created
4489async work.</li>
4490</ul>
4491<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4492<p>This API allocates a work object that is used to execute logic asynchronously.
4493It should be freed using <a href="#n_api_napi_delete_async_work"><code>napi_delete_async_work</code></a> once the work is no longer
4494required.</p>
4495<p><code>async_resource_name</code> should be a null-terminated, UTF-8-encoded string.</p>
4496<p>The <code>async_resource_name</code> identifier is provided by the user and should be
4497representative of the type of async work being performed. It is also recommended
4498to apply namespacing to the identifier, e.g. by including the module name. See
4499the <a href="async_hooks.html#async_hooks_type"><code>async_hooks</code> documentation</a> for more information.</p>
4500<h4>napi_delete_async_work<span><a class="mark" href="#n_api_napi_delete_async_work" id="n_api_napi_delete_async_work">#</a></span></h4>
4501<div class="api_metadata">
4502<span>Added in: v8.0.0</span>
4503<span>N-API version: 1</span>
4504</div>
4505<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_delete_async_work</span><span class="hljs-params">(napi_env env,
4506                                   napi_async_work work)</span>;</code></pre>
4507<ul>
4508<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4509<li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li>
4510</ul>
4511<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4512<p>This API frees a previously allocated work object.</p>
4513<p>This API can be called even if there is a pending JavaScript exception.</p>
4514<h4>napi_queue_async_work<span><a class="mark" href="#n_api_napi_queue_async_work" id="n_api_napi_queue_async_work">#</a></span></h4>
4515<div class="api_metadata">
4516<span>Added in: v8.0.0</span>
4517<span>N-API version: 1</span>
4518</div>
4519<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_queue_async_work</span><span class="hljs-params">(napi_env env,
4520                                  napi_async_work work)</span>;</code></pre>
4521<ul>
4522<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4523<li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li>
4524</ul>
4525<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4526<p>This API requests that the previously allocated work be scheduled
4527for execution. Once it returns successfully, this API must not be called again
4528with the same <code>napi_async_work</code> item or the result will be undefined.</p>
4529<h4>napi_cancel_async_work<span><a class="mark" href="#n_api_napi_cancel_async_work" id="n_api_napi_cancel_async_work">#</a></span></h4>
4530<div class="api_metadata">
4531<span>Added in: v8.0.0</span>
4532<span>N-API version: 1</span>
4533</div>
4534<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_cancel_async_work</span><span class="hljs-params">(napi_env env,
4535                                   napi_async_work work)</span>;</code></pre>
4536<ul>
4537<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4538<li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li>
4539</ul>
4540<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4541<p>This API cancels queued work if it has not yet
4542been started. If it has already started executing, it cannot be
4543cancelled and <code>napi_generic_failure</code> will be returned. If successful,
4544the <code>complete</code> callback will be invoked with a status value of
4545<code>napi_cancelled</code>. The work should not be deleted before the <code>complete</code>
4546callback invocation, even if it has been successfully cancelled.</p>
4547<p>This API can be called even if there is a pending JavaScript exception.</p>
4548</section><section><h3>Custom asynchronous operations<span><a class="mark" href="#n_api_custom_asynchronous_operations" id="n_api_custom_asynchronous_operations">#</a></span></h3>
4549<p>The simple asynchronous work APIs above may not be appropriate for every
4550scenario. When using any other asynchronous mechanism, the following APIs
4551are necessary to ensure an asynchronous operation is properly tracked by
4552the runtime.</p>
4553<h4>napi_async_init<span><a class="mark" href="#n_api_napi_async_init" id="n_api_napi_async_init">#</a></span></h4>
4554<div class="api_metadata">
4555<span>Added in: v8.6.0</span>
4556<span>N-API version: 1</span>
4557</div>
4558<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_async_init</span><span class="hljs-params">(napi_env env,
4559                            napi_value async_resource,
4560                            napi_value async_resource_name,
4561                            napi_async_context* result)</span></code></pre>
4562<ul>
4563<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4564<li><code>[in] async_resource</code>: Object associated with the async work
4565that will be passed to possible <code>async_hooks</code> <a href="async_hooks.html#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a> and can be
4566accessed by <a href="async_hooks.html#async_hooks_async_hooks_executionasyncresource"><code>async_hooks.executionAsyncResource()</code></a>.</li>
4567<li><code>[in] async_resource_name</code>: Identifier for the kind of resource that is being
4568provided for diagnostic information exposed by the <code>async_hooks</code> API.</li>
4569<li><code>[out] result</code>: The initialized async context.</li>
4570</ul>
4571<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4572<p>The <code>async_resource</code> object needs to be kept alive until
4573<a href="#n_api_napi_async_destroy"><code>napi_async_destroy</code></a> to keep <code>async_hooks</code> related API acts correctly. In
4574order to retain ABI compatibility with previous versions, <code>napi_async_context</code>s
4575are not maintaining the strong reference to the <code>async_resource</code> objects to
4576avoid introducing causing memory leaks. However, if the <code>async_resource</code> is
4577garbage collected by JavaScript engine before the <code>napi_async_context</code> was
4578destroyed by <code>napi_async_destroy</code>, calling <code>napi_async_context</code> related APIs
4579like <a href="#n_api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a> and <a href="#n_api_napi_make_callback"><code>napi_make_callback</code></a> can cause
4580problems like loss of async context when using the <code>AsyncLocalStoage</code> API.</p>
4581<p>In order to retain ABI compatibility with previous versions, passing <code>NULL</code>
4582for <code>async_resource</code> does not result in an error. However, this is not
4583recommended as this will result poor results with  <code>async_hooks</code>
4584<a href="async_hooks.html#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a> and <code>async_hooks.executionAsyncResource()</code> as the resource is
4585now required by the underlying <code>async_hooks</code> implementation in order to provide
4586the linkage between async callbacks.</p>
4587<h4>napi_async_destroy<span><a class="mark" href="#n_api_napi_async_destroy" id="n_api_napi_async_destroy">#</a></span></h4>
4588<div class="api_metadata">
4589<span>Added in: v8.6.0</span>
4590<span>N-API version: 1</span>
4591</div>
4592<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_async_destroy</span><span class="hljs-params">(napi_env env,
4593                               napi_async_context async_context)</span>;</code></pre>
4594<ul>
4595<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4596<li><code>[in] async_context</code>: The async context to be destroyed.</li>
4597</ul>
4598<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4599<p>This API can be called even if there is a pending JavaScript exception.</p>
4600<h4>napi_make_callback<span><a class="mark" href="#n_api_napi_make_callback" id="n_api_napi_make_callback">#</a></span></h4>
4601<div class="api_metadata">
4602<details class="changelog"><summary>History</summary>
4603<table>
4604<tbody><tr><th>Version</th><th>Changes</th></tr>
4605<tr><td>v8.6.0</td>
4606<td><p>Added <code>async_context</code> parameter.</p></td></tr>
4607<tr><td>v8.0.0</td>
4608<td><p><span>Added in: v8.0.0</span></p></td></tr>
4609</tbody></table>
4610</details>
4611<span>N-API version: 1</span>
4612</div>
4613<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_make_callback</span><span class="hljs-params">(napi_env env,
4614                                           napi_async_context async_context,
4615                                           napi_value recv,
4616                                           napi_value func,
4617                                           <span class="hljs-type">size_t</span> argc,
4618                                           <span class="hljs-keyword">const</span> napi_value* argv,
4619                                           napi_value* result)</span>;</code></pre>
4620<ul>
4621<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4622<li><code>[in] async_context</code>: Context for the async operation that is
4623invoking the callback. This should normally be a value previously
4624obtained from <a href="#n_api_napi_async_init"><code>napi_async_init</code></a>.
4625In order to retain ABI compatibility with previous versions, passing <code>NULL</code>
4626for <code>async_context</code> does not result in an error. However, this results
4627in incorrect operation of async hooks. Potential issues include loss of
4628async context when using the <code>AsyncLocalStorage</code> API.</li>
4629<li><code>[in] recv</code>: The <code>this</code> value passed to the called function.</li>
4630<li><code>[in] func</code>: <code>napi_value</code> representing the JavaScript function to be invoked.</li>
4631<li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li>
4632<li><code>[in] argv</code>: Array of JavaScript values as <code>napi_value</code> representing the
4633arguments to the function.</li>
4634<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned.</li>
4635</ul>
4636<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4637<p>This method allows a JavaScript function object to be called from a native
4638add-on. This API is similar to <code>napi_call_function</code>. However, it is used to call
4639<em>from</em> native code back <em>into</em> JavaScript <em>after</em> returning from an async
4640operation (when there is no other script on the stack). It is a fairly simple
4641wrapper around <code>node::MakeCallback</code>.</p>
4642<p>Note it is <em>not</em> necessary to use <code>napi_make_callback</code> from within a
4643<code>napi_async_complete_callback</code>; in that situation the callback's async
4644context has already been set up, so a direct call to <code>napi_call_function</code>
4645is sufficient and appropriate. Use of the <code>napi_make_callback</code> function
4646may be required when implementing custom async behavior that does not use
4647<code>napi_create_async_work</code>.</p>
4648<p>Any <code>process.nextTick</code>s or Promises scheduled on the microtask queue by
4649JavaScript during the callback are ran before returning back to C/C++.</p>
4650<h4>napi_open_callback_scope<span><a class="mark" href="#n_api_napi_open_callback_scope" id="n_api_napi_open_callback_scope">#</a></span></h4>
4651<div class="api_metadata">
4652<span>Added in: v9.6.0</span>
4653<span>N-API version: 3</span>
4654</div>
4655<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_open_callback_scope</span><span class="hljs-params">(napi_env env,
4656                                                 napi_value resource_object,
4657                                                 napi_async_context context,
4658                                                 napi_callback_scope* result)</span></code></pre>
4659<ul>
4660<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4661<li><code>[in] resource_object</code>: An object associated with the async work
4662that will be passed to possible <code>async_hooks</code> <a href="async_hooks.html#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>. This
4663parameter has been deprecated and is ignored at runtime. Use the
4664<code>async_resource</code> parameter in <a href="#n_api_napi_async_init"><code>napi_async_init</code></a> instead.</li>
4665<li><code>[in] context</code>: Context for the async operation that is invoking the callback.
4666This should be a value previously obtained from <a href="#n_api_napi_async_init"><code>napi_async_init</code></a>.</li>
4667<li><code>[out] result</code>: The newly created scope.</li>
4668</ul>
4669<p>There are cases (for example, resolving promises) where it is
4670necessary to have the equivalent of the scope associated with a callback
4671in place when making certain Node-API calls. If there is no other script on
4672the stack the <a href="#n_api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a> and
4673<a href="#n_api_napi_close_callback_scope"><code>napi_close_callback_scope</code></a> functions can be used to open/close
4674the required scope.</p>
4675<h4>napi_close_callback_scope<span><a class="mark" href="#n_api_napi_close_callback_scope" id="n_api_napi_close_callback_scope">#</a></span></h4>
4676<div class="api_metadata">
4677<span>Added in: v9.6.0</span>
4678<span>N-API version: 3</span>
4679</div>
4680<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_close_callback_scope</span><span class="hljs-params">(napi_env env,
4681                                                  napi_callback_scope scope)</span></code></pre>
4682<ul>
4683<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4684<li><code>[in] scope</code>: The scope to be closed.</li>
4685</ul>
4686<p>This API can be called even if there is a pending JavaScript exception.</p>
4687</section><section><h3>Version management<span><a class="mark" href="#n_api_version_management" id="n_api_version_management">#</a></span></h3>
4688<h4>napi_get_node_version<span><a class="mark" href="#n_api_napi_get_node_version" id="n_api_napi_get_node_version">#</a></span></h4>
4689<div class="api_metadata">
4690<span>Added in: v8.4.0</span>
4691<span>N-API version: 1</span>
4692</div>
4693<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
4694  <span class="hljs-type">uint32_t</span> major;
4695  <span class="hljs-type">uint32_t</span> minor;
4696  <span class="hljs-type">uint32_t</span> patch;
4697  <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>* release;
4698} napi_node_version;
4699
4700napi_status <span class="hljs-title function_">napi_get_node_version</span><span class="hljs-params">(napi_env env,
4701                                  <span class="hljs-keyword">const</span> napi_node_version** version)</span>;</code></pre>
4702<ul>
4703<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4704<li><code>[out] version</code>: A pointer to version information for Node.js itself.</li>
4705</ul>
4706<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4707<p>This function fills the <code>version</code> struct with the major, minor, and patch
4708version of Node.js that is currently running, and the <code>release</code> field with the
4709value of <a href="process.html#process_process_release"><code>process.release.name</code></a>.</p>
4710<p>The returned buffer is statically allocated and does not need to be freed.</p>
4711<h4>napi_get_version<span><a class="mark" href="#n_api_napi_get_version" id="n_api_napi_get_version">#</a></span></h4>
4712<div class="api_metadata">
4713<span>Added in: v8.0.0</span>
4714<span>N-API version: 1</span>
4715</div>
4716<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_version</span><span class="hljs-params">(napi_env env,
4717                             <span class="hljs-type">uint32_t</span>* result)</span>;</code></pre>
4718<ul>
4719<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4720<li><code>[out] result</code>: The highest version of Node-API supported.</li>
4721</ul>
4722<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4723<p>This API returns the highest Node-API version supported by the
4724Node.js runtime. Node-API is planned to be additive such that
4725newer releases of Node.js may support additional API functions.
4726In order to allow an addon to use a newer function when running with
4727versions of Node.js that support it, while providing
4728fallback behavior when running with Node.js versions that don't
4729support it:</p>
4730<ul>
4731<li>Call <code>napi_get_version()</code> to determine if the API is available.</li>
4732<li>If available, dynamically load a pointer to the function using <code>uv_dlsym()</code>.</li>
4733<li>Use the dynamically loaded pointer to invoke the function.</li>
4734<li>If the function is not available, provide an alternate implementation
4735that does not use the function.</li>
4736</ul>
4737</section><section><h3>Memory management<span><a class="mark" href="#n_api_memory_management" id="n_api_memory_management">#</a></span></h3>
4738<h4>napi_adjust_external_memory<span><a class="mark" href="#n_api_napi_adjust_external_memory" id="n_api_napi_adjust_external_memory">#</a></span></h4>
4739<div class="api_metadata">
4740<span>Added in: v8.5.0</span>
4741<span>N-API version: 1</span>
4742</div>
4743<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_adjust_external_memory</span><span class="hljs-params">(napi_env env,
4744                                                    <span class="hljs-type">int64_t</span> change_in_bytes,
4745                                                    <span class="hljs-type">int64_t</span>* result)</span>;</code></pre>
4746<ul>
4747<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4748<li><code>[in] change_in_bytes</code>: The change in externally allocated memory that is kept
4749alive by JavaScript objects.</li>
4750<li><code>[out] result</code>: The adjusted value</li>
4751</ul>
4752<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4753<p>This function gives V8 an indication of the amount of externally allocated
4754memory that is kept alive by JavaScript objects (i.e. a JavaScript object
4755that points to its own memory allocated by a native module). Registering
4756externally allocated memory will trigger global garbage collections more
4757often than it would otherwise.</p>
4758</section><section><h3>Promises<span><a class="mark" href="#n_api_promises" id="n_api_promises">#</a></span></h3>
4759<p>Node-API provides facilities for creating <code>Promise</code> objects as described in
4760<a href="https://tc39.github.io/ecma262/#sec-promise-objects">Section 25.4</a> of the ECMA specification. It implements promises as a pair of
4761objects. When a promise is created by <code>napi_create_promise()</code>, a "deferred"
4762object is created and returned alongside the <code>Promise</code>. The deferred object is
4763bound to the created <code>Promise</code> and is the only means to resolve or reject the
4764<code>Promise</code> using <code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code>. The
4765deferred object that is created by <code>napi_create_promise()</code> is freed by
4766<code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code>. The <code>Promise</code> object may
4767be returned to JavaScript where it can be used in the usual fashion.</p>
4768<p>For example, to create a promise and pass it to an asynchronous worker:</p>
4769<pre><code class="language-c">napi_deferred deferred;
4770napi_value promise;
4771napi_status status;
4772
4773<span class="hljs-comment">// Create the promise.</span>
4774status = napi_create_promise(env, &#x26;deferred, &#x26;promise);
4775<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
4776
4777<span class="hljs-comment">// Pass the deferred to a function that performs an asynchronous action.</span>
4778do_something_asynchronous(deferred);
4779
4780<span class="hljs-comment">// Return the promise to JS</span>
4781<span class="hljs-keyword">return</span> promise;</code></pre>
4782<p>The above function <code>do_something_asynchronous()</code> would perform its asynchronous
4783action and then it would resolve or reject the deferred, thereby concluding the
4784promise and freeing the deferred:</p>
4785<pre><code class="language-c">napi_deferred deferred;
4786napi_value undefined;
4787napi_status status;
4788
4789<span class="hljs-comment">// Create a value with which to conclude the deferred.</span>
4790status = napi_get_undefined(env, &#x26;undefined);
4791<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
4792
4793<span class="hljs-comment">// Resolve or reject the promise associated with the deferred depending on</span>
4794<span class="hljs-comment">// whether the asynchronous action succeeded.</span>
4795<span class="hljs-keyword">if</span> (asynchronous_action_succeeded) {
4796  status = napi_resolve_deferred(env, deferred, undefined);
4797} <span class="hljs-keyword">else</span> {
4798  status = napi_reject_deferred(env, deferred, undefined);
4799}
4800<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
4801
4802<span class="hljs-comment">// At this point the deferred has been freed, so we should assign NULL to it.</span>
4803deferred = <span class="hljs-literal">NULL</span>;</code></pre>
4804<h4>napi_create_promise<span><a class="mark" href="#n_api_napi_create_promise" id="n_api_napi_create_promise">#</a></span></h4>
4805<div class="api_metadata">
4806<span>Added in: v8.5.0</span>
4807<span>N-API version: 1</span>
4808</div>
4809<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_promise</span><span class="hljs-params">(napi_env env,
4810                                napi_deferred* deferred,
4811                                napi_value* promise)</span>;</code></pre>
4812<ul>
4813<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4814<li><code>[out] deferred</code>: A newly created deferred object which can later be passed to
4815<code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code> to resolve resp. reject
4816the associated promise.</li>
4817<li><code>[out] promise</code>: The JavaScript promise associated with the deferred object.</li>
4818</ul>
4819<p>Returns <code>napi_ok</code> if the API succeeded.</p>
4820<p>This API creates a deferred object and a JavaScript promise.</p>
4821<h4>napi_resolve_deferred<span><a class="mark" href="#n_api_napi_resolve_deferred" id="n_api_napi_resolve_deferred">#</a></span></h4>
4822<div class="api_metadata">
4823<span>Added in: v8.5.0</span>
4824<span>N-API version: 1</span>
4825</div>
4826<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_resolve_deferred</span><span class="hljs-params">(napi_env env,
4827                                  napi_deferred deferred,
4828                                  napi_value resolution)</span>;</code></pre>
4829<ul>
4830<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4831<li><code>[in] deferred</code>: The deferred object whose associated promise to resolve.</li>
4832<li><code>[in] resolution</code>: The value with which to resolve the promise.</li>
4833</ul>
4834<p>This API resolves a JavaScript promise by way of the deferred object
4835with which it is associated. Thus, it can only be used to resolve JavaScript
4836promises for which the corresponding deferred object is available. This
4837effectively means that the promise must have been created using
4838<code>napi_create_promise()</code> and the deferred object returned from that call must
4839have been retained in order to be passed to this API.</p>
4840<p>The deferred object is freed upon successful completion.</p>
4841<h4>napi_reject_deferred<span><a class="mark" href="#n_api_napi_reject_deferred" id="n_api_napi_reject_deferred">#</a></span></h4>
4842<div class="api_metadata">
4843<span>Added in: v8.5.0</span>
4844<span>N-API version: 1</span>
4845</div>
4846<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_reject_deferred</span><span class="hljs-params">(napi_env env,
4847                                 napi_deferred deferred,
4848                                 napi_value rejection)</span>;</code></pre>
4849<ul>
4850<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4851<li><code>[in] deferred</code>: The deferred object whose associated promise to resolve.</li>
4852<li><code>[in] rejection</code>: The value with which to reject the promise.</li>
4853</ul>
4854<p>This API rejects a JavaScript promise by way of the deferred object
4855with which it is associated. Thus, it can only be used to reject JavaScript
4856promises for which the corresponding deferred object is available. This
4857effectively means that the promise must have been created using
4858<code>napi_create_promise()</code> and the deferred object returned from that call must
4859have been retained in order to be passed to this API.</p>
4860<p>The deferred object is freed upon successful completion.</p>
4861<h4>napi_is_promise<span><a class="mark" href="#n_api_napi_is_promise" id="n_api_napi_is_promise">#</a></span></h4>
4862<div class="api_metadata">
4863<span>Added in: v8.5.0</span>
4864<span>N-API version: 1</span>
4865</div>
4866<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_promise</span><span class="hljs-params">(napi_env env,
4867                            napi_value value,
4868                            <span class="hljs-type">bool</span>* is_promise)</span>;</code></pre>
4869<ul>
4870<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4871<li><code>[in] value</code>: The value to examine</li>
4872<li><code>[out] is_promise</code>: Flag indicating whether <code>promise</code> is a native promise
4873object (that is, a promise object created by the underlying engine).</li>
4874</ul>
4875</section><section><h3>Script execution<span><a class="mark" href="#n_api_script_execution" id="n_api_script_execution">#</a></span></h3>
4876<p>Node-API provides an API for executing a string containing JavaScript using the
4877underlying JavaScript engine.</p>
4878<h4>napi_run_script<span><a class="mark" href="#n_api_napi_run_script" id="n_api_napi_run_script">#</a></span></h4>
4879<div class="api_metadata">
4880<span>Added in: v8.5.0</span>
4881<span>N-API version: 1</span>
4882</div>
4883<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_run_script</span><span class="hljs-params">(napi_env env,
4884                                        napi_value script,
4885                                        napi_value* result)</span>;</code></pre>
4886<ul>
4887<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4888<li><code>[in] script</code>: A JavaScript string containing the script to execute.</li>
4889<li><code>[out] result</code>: The value resulting from having executed the script.</li>
4890</ul>
4891<p>This function executes a string of JavaScript code and returns its result with
4892the following caveats:</p>
4893<ul>
4894<li>Unlike <code>eval</code>, this function does not allow the script to access the current
4895lexical scope, and therefore also does not allow to access the
4896<a href="modules.html#modules_the_module_scope">module scope</a>, meaning that pseudo-globals such as <code>require</code> will not be
4897available.</li>
4898<li>The script can access the <a href="globals.html">global scope</a>. Function and <code>var</code> declarations
4899in the script will be added to the <a href="globals.html#globals_global"><code>global</code></a> object. Variable declarations
4900made using <code>let</code> and <code>const</code> will be visible globally, but will not be added
4901to the <a href="globals.html#globals_global"><code>global</code></a> object.</li>
4902<li>The value of <code>this</code> is <a href="globals.html#globals_global"><code>global</code></a> within the script.</li>
4903</ul>
4904</section><section><h3>libuv event loop<span><a class="mark" href="#n_api_libuv_event_loop" id="n_api_libuv_event_loop">#</a></span></h3>
4905<p>Node-API provides a function for getting the current event loop associated with
4906a specific <code>napi_env</code>.</p>
4907<h4>napi_get_uv_event_loop<span><a class="mark" href="#n_api_napi_get_uv_event_loop" id="n_api_napi_get_uv_event_loop">#</a></span></h4>
4908<div class="api_metadata">
4909<span>Added in: v9.3.0, v8.10.0</span>
4910<span>N-API version: 2</span>
4911</div>
4912<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_get_uv_event_loop</span><span class="hljs-params">(napi_env env,
4913                                               <span class="hljs-keyword">struct</span> uv_loop_s** loop)</span>;</code></pre>
4914<ul>
4915<li><code>[in] env</code>: The environment that the API is invoked under.</li>
4916<li><code>[out] loop</code>: The current libuv loop instance.</li>
4917</ul>
4918</section><section><h3>Asynchronous thread-safe function calls<span><a class="mark" href="#n_api_asynchronous_thread_safe_function_calls" id="n_api_asynchronous_thread_safe_function_calls">#</a></span></h3>
4919<p>JavaScript functions can normally only be called from a native addon's main
4920thread. If an addon creates additional threads, then Node-API functions that
4921require a <code>napi_env</code>, <code>napi_value</code>, or <code>napi_ref</code> must not be called from those
4922threads.</p>
4923<p>When an addon has additional threads and JavaScript functions need to be invoked
4924based on the processing completed by those threads, those threads must
4925communicate with the addon's main thread so that the main thread can invoke the
4926JavaScript function on their behalf. The thread-safe function APIs provide an
4927easy way to do this.</p>
4928<p>These APIs provide the type <code>napi_threadsafe_function</code> as well as APIs to
4929create, destroy, and call objects of this type.
4930<code>napi_create_threadsafe_function()</code> creates a persistent reference to a
4931<code>napi_value</code> that holds a JavaScript function which can be called from multiple
4932threads. The calls happen asynchronously. This means that values with which the
4933JavaScript callback is to be called will be placed in a queue, and, for each
4934value in the queue, a call will eventually be made to the JavaScript function.</p>
4935<p>Upon creation of a <code>napi_threadsafe_function</code> a <code>napi_finalize</code> callback can be
4936provided. This callback will be invoked on the main thread when the thread-safe
4937function is about to be destroyed. It receives the context and the finalize data
4938given during construction, and provides an opportunity for cleaning up after the
4939threads e.g. by calling <code>uv_thread_join()</code>. <strong>Aside from the main loop thread,
4940no threads should be using the thread-safe function after the finalize callback
4941completes.</strong></p>
4942<p>The <code>context</code> given during the call to <code>napi_create_threadsafe_function()</code> can
4943be retrieved from any thread with a call to
4944<code>napi_get_threadsafe_function_context()</code>.</p>
4945<h4>Calling a thread-safe function<span><a class="mark" href="#n_api_calling_a_thread_safe_function" id="n_api_calling_a_thread_safe_function">#</a></span></h4>
4946<p><code>napi_call_threadsafe_function()</code> can be used for initiating a call into
4947JavaScript. <code>napi_call_threadsafe_function()</code> accepts a parameter which controls
4948whether the API behaves blockingly. If set to <code>napi_tsfn_nonblocking</code>, the API
4949behaves non-blockingly, returning <code>napi_queue_full</code> if the queue was full,
4950preventing data from being successfully added to the queue. If set to
4951<code>napi_tsfn_blocking</code>, the API blocks until space becomes available in the queue.
4952<code>napi_call_threadsafe_function()</code> never blocks if the thread-safe function was
4953created with a maximum queue size of 0.</p>
4954<p><code>napi_call_threadsafe_function()</code> should not be called with <code>napi_tsfn_blocking</code>
4955from a JavaScript thread, because, if the queue is full, it may cause the
4956JavaScript thread to deadlock.</p>
4957<p>The actual call into JavaScript is controlled by the callback given via the
4958<code>call_js_cb</code> parameter. <code>call_js_cb</code> is invoked on the main thread once for each
4959value that was placed into the queue by a successful call to
4960<code>napi_call_threadsafe_function()</code>. If such a callback is not given, a default
4961callback will be used, and the resulting JavaScript call will have no arguments.
4962The <code>call_js_cb</code> callback receives the JavaScript function to call as a
4963<code>napi_value</code> in its parameters, as well as the <code>void*</code> context pointer used when
4964creating the <code>napi_threadsafe_function</code>, and the next data pointer that was
4965created by one of the secondary threads. The callback can then use an API such
4966as <code>napi_call_function()</code> to call into JavaScript.</p>
4967<p>The callback may also be invoked with <code>env</code> and <code>call_js_cb</code> both set to <code>NULL</code>
4968to indicate that calls into JavaScript are no longer possible, while items
4969remain in the queue that may need to be freed. This normally occurs when the
4970Node.js process exits while there is a thread-safe function still active.</p>
4971<p>It is not necessary to call into JavaScript via <code>napi_make_callback()</code> because
4972Node-API runs <code>call_js_cb</code> in a context appropriate for callbacks.</p>
4973<h4>Reference counting of thread-safe functions<span><a class="mark" href="#n_api_reference_counting_of_thread_safe_functions" id="n_api_reference_counting_of_thread_safe_functions">#</a></span></h4>
4974<p>Threads can be added to and removed from a <code>napi_threadsafe_function</code> object
4975during its existence. Thus, in addition to specifying an initial number of
4976threads upon creation, <code>napi_acquire_threadsafe_function</code> can be called to
4977indicate that a new thread will start making use of the thread-safe function.
4978Similarly, <code>napi_release_threadsafe_function</code> can be called to indicate that an
4979existing thread will stop making use of the thread-safe function.</p>
4980<p><code>napi_threadsafe_function</code> objects are destroyed when every thread which uses
4981the object has called <code>napi_release_threadsafe_function()</code> or has received a
4982return status of <code>napi_closing</code> in response to a call to
4983<code>napi_call_threadsafe_function</code>. The queue is emptied before the
4984<code>napi_threadsafe_function</code> is destroyed. <code>napi_release_threadsafe_function()</code>
4985should be the last API call made in conjunction with a given
4986<code>napi_threadsafe_function</code>, because after the call completes, there is no
4987guarantee that the <code>napi_threadsafe_function</code> is still allocated. For the same
4988reason, do not use a thread-safe function
4989after receiving a return value of <code>napi_closing</code> in response to a call to
4990<code>napi_call_threadsafe_function</code>. Data associated with the
4991<code>napi_threadsafe_function</code> can be freed in its <code>napi_finalize</code> callback which
4992was passed to <code>napi_create_threadsafe_function()</code>. The parameter
4993<code>initial_thread_count</code> of <code>napi_create_threadsafe_function</code> marks the initial
4994number of aquisitions of the thread-safe functions, instead of calling
4995<code>napi_acquire_threadsafe_function</code> multiple times at creation.</p>
4996<p>Once the number of threads making use of a <code>napi_threadsafe_function</code> reaches
4997zero, no further threads can start making use of it by calling
4998<code>napi_acquire_threadsafe_function()</code>. In fact, all subsequent API calls
4999associated with it, except <code>napi_release_threadsafe_function()</code>, will return an
5000error value of <code>napi_closing</code>.</p>
5001<p>The thread-safe function can be "aborted" by giving a value of <code>napi_tsfn_abort</code>
5002to <code>napi_release_threadsafe_function()</code>. This will cause all subsequent APIs
5003associated with the thread-safe function except
5004<code>napi_release_threadsafe_function()</code> to return <code>napi_closing</code> even before its
5005reference count reaches zero. In particular, <code>napi_call_threadsafe_function()</code>
5006will return <code>napi_closing</code>, thus informing the threads that it is no longer
5007possible to make asynchronous calls to the thread-safe function. This can be
5008used as a criterion for terminating the thread. <strong>Upon receiving a return value
5009of <code>napi_closing</code> from <code>napi_call_threadsafe_function()</code> a thread must not use
5010the thread-safe function anymore because it is no longer guaranteed to
5011be allocated.</strong></p>
5012<h4>Deciding whether to keep the process running<span><a class="mark" href="#n_api_deciding_whether_to_keep_the_process_running" id="n_api_deciding_whether_to_keep_the_process_running">#</a></span></h4>
5013<p>Similarly to libuv handles, thread-safe functions can be "referenced" and
5014"unreferenced". A "referenced" thread-safe function will cause the event loop on
5015the thread on which it is created to remain alive until the thread-safe function
5016is destroyed. In contrast, an "unreferenced" thread-safe function will not
5017prevent the event loop from exiting. The APIs <code>napi_ref_threadsafe_function</code> and
5018<code>napi_unref_threadsafe_function</code> exist for this purpose.</p>
5019<p>Neither does <code>napi_unref_threadsafe_function</code> mark the thread-safe functions as
5020able to be destroyed nor does <code>napi_ref_threadsafe_function</code> prevent it from
5021being destroyed.</p>
5022<h4>napi_create_threadsafe_function<span><a class="mark" href="#n_api_napi_create_threadsafe_function" id="n_api_napi_create_threadsafe_function">#</a></span></h4>
5023<div class="api_metadata">
5024<details class="changelog"><summary>History</summary>
5025<table>
5026<tbody><tr><th>Version</th><th>Changes</th></tr>
5027<tr><td>v12.6.0, v10.17.0</td>
5028<td><p>Made <code>func</code> parameter optional with custom <code>call_js_cb</code>.</p></td></tr>
5029<tr><td>v10.6.0</td>
5030<td><p><span>Added in: v10.6.0</span></p></td></tr>
5031</tbody></table>
5032</details>
5033<span>N-API version: 4</span>
5034</div>
5035<pre><code class="language-c">NAPI_EXTERN napi_status
5036<span class="hljs-title function_">napi_create_threadsafe_function</span><span class="hljs-params">(napi_env env,
5037                                napi_value func,
5038                                napi_value async_resource,
5039                                napi_value async_resource_name,
5040                                <span class="hljs-type">size_t</span> max_queue_size,
5041                                <span class="hljs-type">size_t</span> initial_thread_count,
5042                                <span class="hljs-type">void</span>* thread_finalize_data,
5043                                napi_finalize thread_finalize_cb,
5044                                <span class="hljs-type">void</span>* context,
5045                                napi_threadsafe_function_call_js call_js_cb,
5046                                napi_threadsafe_function* result)</span>;</code></pre>
5047<ul>
5048<li><code>[in] env</code>: The environment that the API is invoked under.</li>
5049<li><code>[in] func</code>: An optional JavaScript function to call from another thread. It
5050must be provided if <code>NULL</code> is passed to <code>call_js_cb</code>.</li>
5051<li><code>[in] async_resource</code>: An optional object associated with the async work that
5052will be passed to possible <code>async_hooks</code> <a href="async_hooks.html#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.</li>
5053<li><code>[in] async_resource_name</code>: A JavaScript string to provide an identifier for
5054the kind of resource that is being provided for diagnostic information exposed
5055by the <code>async_hooks</code> API.</li>
5056<li><code>[in] max_queue_size</code>: Maximum size of the queue. <code>0</code> for no limit.</li>
5057<li><code>[in] initial_thread_count</code>: The initial number of acquisitions, i.e. the
5058initial number of threads, including the main thread, which will be making use
5059of this function.</li>
5060<li><code>[in] thread_finalize_data</code>: Optional data to be passed to <code>thread_finalize_cb</code>.</li>
5061<li><code>[in] thread_finalize_cb</code>: Optional function to call when the
5062<code>napi_threadsafe_function</code> is being destroyed.</li>
5063<li><code>[in] context</code>: Optional data to attach to the resulting
5064<code>napi_threadsafe_function</code>.</li>
5065<li><code>[in] call_js_cb</code>: Optional callback which calls the JavaScript function in
5066response to a call on a different thread. This callback will be called on the
5067main thread. If not given, the JavaScript function will be called with no
5068parameters and with <code>undefined</code> as its <code>this</code> value.
5069<a href="#n_api_napi_threadsafe_function_call_js"><code>napi_threadsafe_function_call_js</code></a> provides more details.</li>
5070<li><code>[out] result</code>: The asynchronous thread-safe JavaScript function.</li>
5071</ul>
5072<h4>napi_get_threadsafe_function_context<span><a class="mark" href="#n_api_napi_get_threadsafe_function_context" id="n_api_napi_get_threadsafe_function_context">#</a></span></h4>
5073<div class="api_metadata">
5074<span>Added in: v10.6.0</span>
5075<span>N-API version: 4</span>
5076</div>
5077<pre><code class="language-c">NAPI_EXTERN napi_status
5078<span class="hljs-title function_">napi_get_threadsafe_function_context</span><span class="hljs-params">(napi_threadsafe_function func,
5079                                     <span class="hljs-type">void</span>** result)</span>;</code></pre>
5080<ul>
5081<li><code>[in] func</code>: The thread-safe function for which to retrieve the context.</li>
5082<li><code>[out] result</code>: The location where to store the context.</li>
5083</ul>
5084<p>This API may be called from any thread which makes use of <code>func</code>.</p>
5085<h4>napi_call_threadsafe_function<span><a class="mark" href="#n_api_napi_call_threadsafe_function" id="n_api_napi_call_threadsafe_function">#</a></span></h4>
5086<div class="api_metadata">
5087<details class="changelog"><summary>History</summary>
5088<table>
5089<tbody><tr><th>Version</th><th>Changes</th></tr>
5090<tr><td>v14.5.0</td>
5091<td><p>Support for <code>napi_would_deadlock</code> has been reverted.</p></td></tr>
5092<tr><td>v14.1.0</td>
5093<td><p>Return <code>napi_would_deadlock</code> when called with <code>napi_tsfn_blocking</code> from the main thread or a worker thread and the queue is full.</p></td></tr>
5094<tr><td>v10.6.0</td>
5095<td><p><span>Added in: v10.6.0</span></p></td></tr>
5096</tbody></table>
5097</details>
5098<span>N-API version: 4</span>
5099</div>
5100<pre><code class="language-c">NAPI_EXTERN napi_status
5101<span class="hljs-title function_">napi_call_threadsafe_function</span><span class="hljs-params">(napi_threadsafe_function func,
5102                              <span class="hljs-type">void</span>* data,
5103                              napi_threadsafe_function_call_mode is_blocking)</span>;</code></pre>
5104<ul>
5105<li><code>[in] func</code>: The asynchronous thread-safe JavaScript function to invoke.</li>
5106<li><code>[in] data</code>: Data to send into JavaScript via the callback <code>call_js_cb</code>
5107provided during the creation of the thread-safe JavaScript function.</li>
5108<li><code>[in] is_blocking</code>: Flag whose value can be either <code>napi_tsfn_blocking</code> to
5109indicate that the call should block if the queue is full or
5110<code>napi_tsfn_nonblocking</code> to indicate that the call should return immediately
5111with a status of <code>napi_queue_full</code> whenever the queue is full.</li>
5112</ul>
5113<p>This API should not be called with <code>napi_tsfn_blocking</code> from a JavaScript
5114thread, because, if the queue is full, it may cause the JavaScript thread to
5115deadlock.</p>
5116<p>This API will return <code>napi_closing</code> if <code>napi_release_threadsafe_function()</code> was
5117called with <code>abort</code> set to <code>napi_tsfn_abort</code> from any thread. The value is only
5118added to the queue if the API returns <code>napi_ok</code>.</p>
5119<p>This API may be called from any thread which makes use of <code>func</code>.</p>
5120<h4>napi_acquire_threadsafe_function<span><a class="mark" href="#n_api_napi_acquire_threadsafe_function" id="n_api_napi_acquire_threadsafe_function">#</a></span></h4>
5121<div class="api_metadata">
5122<span>Added in: v10.6.0</span>
5123<span>N-API version: 4</span>
5124</div>
5125<pre><code class="language-c">NAPI_EXTERN napi_status
5126<span class="hljs-title function_">napi_acquire_threadsafe_function</span><span class="hljs-params">(napi_threadsafe_function func)</span>;</code></pre>
5127<ul>
5128<li><code>[in] func</code>: The asynchronous thread-safe JavaScript function to start making
5129use of.</li>
5130</ul>
5131<p>A thread should call this API before passing <code>func</code> to any other thread-safe
5132function APIs to indicate that it will be making use of <code>func</code>. This prevents
5133<code>func</code> from being destroyed when all other threads have stopped making use of
5134it.</p>
5135<p>This API may be called from any thread which will start making use of <code>func</code>.</p>
5136<h4>napi_release_threadsafe_function<span><a class="mark" href="#n_api_napi_release_threadsafe_function" id="n_api_napi_release_threadsafe_function">#</a></span></h4>
5137<div class="api_metadata">
5138<span>Added in: v10.6.0</span>
5139<span>N-API version: 4</span>
5140</div>
5141<pre><code class="language-c">NAPI_EXTERN napi_status
5142<span class="hljs-title function_">napi_release_threadsafe_function</span><span class="hljs-params">(napi_threadsafe_function func,
5143                                 napi_threadsafe_function_release_mode mode)</span>;</code></pre>
5144<ul>
5145<li><code>[in] func</code>: The asynchronous thread-safe JavaScript function whose reference
5146count to decrement.</li>
5147<li><code>[in] mode</code>: Flag whose value can be either <code>napi_tsfn_release</code> to indicate
5148that the current thread will make no further calls to the thread-safe
5149function, or <code>napi_tsfn_abort</code> to indicate that in addition to the current
5150thread, no other thread should make any further calls to the thread-safe
5151function. If set to <code>napi_tsfn_abort</code>, further calls to
5152<code>napi_call_threadsafe_function()</code> will return <code>napi_closing</code>, and no further
5153values will be placed in the queue.</li>
5154</ul>
5155<p>A thread should call this API when it stops making use of <code>func</code>. Passing <code>func</code>
5156to any thread-safe APIs after having called this API has undefined results, as
5157<code>func</code> may have been destroyed.</p>
5158<p>This API may be called from any thread which will stop making use of <code>func</code>.</p>
5159<h4>napi_ref_threadsafe_function<span><a class="mark" href="#n_api_napi_ref_threadsafe_function" id="n_api_napi_ref_threadsafe_function">#</a></span></h4>
5160<div class="api_metadata">
5161<span>Added in: v10.6.0</span>
5162<span>N-API version: 4</span>
5163</div>
5164<pre><code class="language-c">NAPI_EXTERN napi_status
5165<span class="hljs-title function_">napi_ref_threadsafe_function</span><span class="hljs-params">(napi_env env, napi_threadsafe_function func)</span>;</code></pre>
5166<ul>
5167<li><code>[in] env</code>: The environment that the API is invoked under.</li>
5168<li><code>[in] func</code>: The thread-safe function to reference.</li>
5169</ul>
5170<p>This API is used to indicate that the event loop running on the main thread
5171should not exit until <code>func</code> has been destroyed. Similar to <a href="https://docs.libuv.org/en/v1.x/handle.html#c.uv_ref"><code>uv_ref</code></a> it is
5172also idempotent.</p>
5173<p>Neither does <code>napi_unref_threadsafe_function</code> mark the thread-safe functions as
5174able to be destroyed nor does <code>napi_ref_threadsafe_function</code> prevent it from
5175being destroyed. <code>napi_acquire_threadsafe_function</code> and
5176<code>napi_release_threadsafe_function</code> are available for that purpose.</p>
5177<p>This API may only be called from the main thread.</p>
5178<h4>napi_unref_threadsafe_function<span><a class="mark" href="#n_api_napi_unref_threadsafe_function" id="n_api_napi_unref_threadsafe_function">#</a></span></h4>
5179<div class="api_metadata">
5180<span>Added in: v10.6.0</span>
5181<span>N-API version: 4</span>
5182</div>
5183<pre><code class="language-c">NAPI_EXTERN napi_status
5184<span class="hljs-title function_">napi_unref_threadsafe_function</span><span class="hljs-params">(napi_env env, napi_threadsafe_function func)</span>;</code></pre>
5185<ul>
5186<li><code>[in] env</code>: The environment that the API is invoked under.</li>
5187<li><code>[in] func</code>: The thread-safe function to unreference.</li>
5188</ul>
5189<p>This API is used to indicate that the event loop running on the main thread
5190may exit before <code>func</code> is destroyed. Similar to <a href="https://docs.libuv.org/en/v1.x/handle.html#c.uv_unref"><code>uv_unref</code></a> it is also
5191idempotent.</p>
5192<p>This API may only be called from the main thread.</p>
5193</section><section><h3>Miscellaneous utilities<span><a class="mark" href="#n_api_miscellaneous_utilities" id="n_api_miscellaneous_utilities">#</a></span></h3>
5194</section><section><h3>node_api_get_module_file_name<span><a class="mark" href="#n_api_node_api_get_module_file_name" id="n_api_node_api_get_module_file_name">#</a></span></h3>
5195<div class="api_metadata">
5196<span>Added in: v14.18.0</span>
5197</div>
5198<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
5199<pre><code class="language-c">NAPI_EXTERN napi_status
5200<span class="hljs-title function_">node_api_get_module_file_name</span><span class="hljs-params">(napi_env env, <span class="hljs-keyword">const</span> <span class="hljs-type">char</span>** result)</span>;
5201</code></pre>
5202<ul>
5203<li><code>[in] env</code>: The environment that the API is invoked under.</li>
5204<li><code>[out] result</code>: A URL containing the absolute path of the
5205location from which the add-on was loaded. For a file on the local
5206file system it will start with <code>file://</code>. The string is null-terminated and
5207owned by <code>env</code> and must thus not be modified or freed.</li>
5208</ul>
5209<p><code>result</code> may be an empty string if the add-on loading process fails to establish
5210the add-on's file name during loading.</p></section>
5211        <!-- API END -->
5212      </div>
5213    </div>
5214  </div>
5215  <script>
5216    'use strict';
5217    {
5218      const kCustomPreference = 'customDarkTheme';
5219      const userSettings = sessionStorage.getItem(kCustomPreference);
5220      const themeToggleButton = document.getElementById('theme-toggle-btn');
5221      if (userSettings === null && window.matchMedia) {
5222        const mq = window.matchMedia('(prefers-color-scheme: dark)');
5223        if ('onchange' in mq) {
5224          function mqChangeListener(e) {
5225            document.body.classList.toggle('dark-mode', e.matches);
5226          }
5227          mq.addEventListener('change', mqChangeListener);
5228          if (themeToggleButton) {
5229            themeToggleButton.addEventListener('click', function() {
5230              mq.removeEventListener('change', mqChangeListener);
5231            }, { once: true });
5232          }
5233        }
5234        if (mq.matches) {
5235          document.body.classList.add('dark-mode');
5236        }
5237      } else if (userSettings === 'true') {
5238        document.body.classList.add('dark-mode');
5239      }
5240      if (themeToggleButton) {
5241        themeToggleButton.hidden = false;
5242        themeToggleButton.addEventListener('click', function() {
5243          sessionStorage.setItem(
5244            kCustomPreference,
5245            document.body.classList.toggle('dark-mode')
5246          );
5247        });
5248      }
5249    }
5250  </script>
5251</body>
5252</html>
5253