Skip to content

Commit 0a0a56a

Browse files
fhinkelMylesBorins
authored andcommitted
doc: add "Hello world" example for N-API
Our Addons documentation has a "Hello world" example that outlines all steps to build it. Adding the sources for this "Hello world" example for N-API. PR-URL: #17425 Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Rich Trott <[email protected]> Reviewed-By: Tobias Nießen <[email protected]> Reviewed-By: Michael Dawson <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 865c452 commit 0a0a56a

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

doc/api/addons.md

+36-1
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ illustration of how it can be used.
221221
> Stability: 1 - Experimental
222222
223223
N-API is an API for building native Addons. It is independent from
224-
the underlying JavaScript runtime (ex V8) and is maintained as part of
224+
the underlying JavaScript runtime (e.g., V8) and is maintained as part of
225225
Node.js itself. This API will be Application Binary Interface (ABI) stable
226226
across version of Node.js. It is intended to insulate Addons from
227227
changes in the underlying JavaScript engine and allow modules
@@ -232,6 +232,41 @@ set of APIs that are used by the native code. Instead of using the V8
232232
or [Native Abstractions for Node.js][] APIs, the functions available
233233
in the N-API are used.
234234

235+
To use N-API in the above "Hello world" example, replace the content of
236+
`hello.cc` with the following. All other instructions remain the same.
237+
238+
```cpp
239+
// hello.cc using N-API
240+
#include <node_api.h>
241+
242+
namespace demo {
243+
244+
napi_value Method(napi_env env, napi_callback_info args) {
245+
napi_value greeting;
246+
napi_status status;
247+
248+
status = napi_create_string_utf8(env, "hello", 6, &greeting);
249+
if (status != napi_ok) return nullptr;
250+
return greeting;
251+
}
252+
253+
napi_value init(napi_env env, napi_value exports) {
254+
napi_status status;
255+
napi_value fn;
256+
257+
status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
258+
if (status != napi_ok) return nullptr;
259+
260+
status = napi_set_named_property(env, exports, "hello", fn);
261+
if (status != napi_ok) return nullptr;
262+
return exports;
263+
}
264+
265+
NAPI_MODULE(NODE_GYP_MODULE_NAME, init)
266+
267+
} // namespace demo
268+
```
269+
235270
The functions available and how to use them are documented in the
236271
section titled [C/C++ Addons - N-API](n-api.html).
237272

0 commit comments

Comments
 (0)