C++ addons | Node.js v21.7.3 Documentation
https://nodejs.org/docs/latest-v21.x/api/addons.html • 107 KB fetched
Open original page
C++ addons | Node.js v21.7.3 Documentation
Node.js
* About this documentation
* Usage and example
* Assertion testing
* Asynchronous context tracking
* Async hooks
* Buffer
* C++ addons
* C/C++ addons with Node-API
* C++ embedder API
* Child processes
* Cluster
* Command-line options
* Console
* Corepack
* Crypto
* Debugger
* Deprecated APIs
* Diagnostics Channel
* DNS
* Domain
* Errors
* Events
* File system
* Globals
* HTTP
* HTTP/2
* HTTPS
* Inspector
* Internationalization
* Modules: CommonJS modules
* Modules: ECMAScript modules
* Modules: node:module API
* Modules: Packages
* Net
* OS
* Path
* Performance hooks
* Permissions
* Process
* Punycode
* Query strings
* Readline
* REPL
* Report
* Single executable applications
* Stream
* String decoder
* Test runner
* Timers
* TLS/SSL
* Trace events
* TTY
* UDP/datagram
* URL
* Utilities
* V8
* VM
* WASI
* Web Crypto API
* Web Streams API
* Worker threads
* Zlib
* Code repository and issue tracker
Node.js v21.7.3 documentation
* Node.js v21.7.3
*
► ▼
Table of contents
* C++ addons
* Hello world
* Context-aware addons
* Worker support
* Building
* Linking to libraries included with Node.js
* Loading addons using require()
* Native abstractions for Node.js
* Node-API
* Addon examples
* Function arguments
* Callbacks
* Object factory
* Function factory
* Wrapping C++ objects
* Factory of wrapped objects
* Passing wrapped objects around
*
► ▼
Index
* About this documentation
* Usage and example
*
Index
* Assertion testing
* Asynchronous context tracking
* Async hooks
* Buffer
* C++ addons
* C/C++ addons with Node-API
* C++ embedder API
* Child processes
* Cluster
* Command-line options
* Console
* Corepack
* Crypto
* Debugger
* Deprecated APIs
* Diagnostics Channel
* DNS
* Domain
* Errors
* Events
* File system
* Globals
* HTTP
* HTTP/2
* HTTPS
* Inspector
* Internationalization
* Modules: CommonJS modules
* Modules: ECMAScript modules
* Modules: node:module API
* Modules: Packages
* Net
* OS
* Path
* Performance hooks
* Permissions
* Process
* Punycode
* Query strings
* Readline
* REPL
* Report
* Single executable applications
* Stream
* String decoder
* Test runner
* Timers
* TLS/SSL
* Trace events
* TTY
* UDP/datagram
* URL
* Utilities
* V8
* VM
* WASI
* Web Crypto API
* Web Streams API
* Worker threads
* Zlib
* Code repository and issue tracker
*
► ▼
Other versions
* 21.x
* 20.x LTS
* 19.x
* 18.x LTS
* 17.x
* 16.x
* 15.x
* 14.x
* 13.x
* 12.x
* 11.x
* 10.x
* 9.x
* 8.x
* 7.x
* 6.x
* 5.x
* 4.x
* 0.12.x
* 0.10.x
*
► ▼
Options
*
View on single page
*
View as JSON
* Edit on GitHub
Table of contents
* C++ addons
* Hello world
* Context-aware addons
* Worker support
* Building
* Linking to libraries included with Node.js
* Loading addons using require()
* Native abstractions for Node.js
* Node-API
* Addon examples
* Function arguments
* Callbacks
* Object factory
* Function factory
* Wrapping C++ objects
* Factory of wrapped objects
* Passing wrapped objects around
C++ addons #
Addons are dynamically-linked shared objects written in C++. The
require() function can load addons as ordinary Node.js modules.
Addons provide an interface between JavaScript and C/C++ libraries.
There are three options for implementing addons: Node-API, nan, or direct
use of internal V8, libuv, and Node.js libraries. Unless there is a need for
direct access to functionality which is not exposed by Node-API, use Node-API.
Refer to C/C++ addons with Node-API for more information on
Node-API.
When not using Node-API, implementing addons is complicated,
involving knowledge of several components and APIs:
*
V8 : the C++ library Node.js uses to provide the
JavaScript implementation. V8 provides the mechanisms for creating objects,
calling functions, etc. V8's API is documented mostly in the
v8.h header file ( deps/v8/include/v8.h in the Node.js source
tree), which is also available online .
*
libuv : The C library that implements the Node.js event loop, its worker
threads and all of the asynchronous behaviors of the platform. It also
serves as a cross-platform abstraction library, giving easy, POSIX-like
access across all major operating systems to many common system tasks, such
as interacting with the file system, sockets, timers, and system events. libuv
also provides a threading abstraction similar to POSIX threads for
more sophisticated asynchronous addons that need to move beyond the
standard event loop. Addon authors should
avoid blocking the event loop with I/O or other time-intensive tasks by
offloading work via libuv to non-blocking system operations, worker threads,
or a custom use of libuv threads.
*
Internal Node.js libraries. Node.js itself exports C++ APIs that addons can
use, the most important of which is the node::ObjectWrap class.
*
Node.js includes other statically linked libraries including OpenSSL. These
other libraries are located in the deps/ directory in the Node.js source
tree. Only the libuv, OpenSSL, V8, and zlib symbols are purposefully
re-exported by Node.js and may be used to various extents by addons. See
Linking to libraries included with Node.js for additional information.
All of the following examples are available for download and may
be used as the starting-point for an addon.
Hello world #
This "Hello world" example is a simple addon, written in C++, that is the
equivalent of the following JavaScript code:
module . exports . hello = () => 'world' ; copy
First, create the file hello.cc :
// hello.cc
# include <node.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void Method ( const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args. GetIsolate ();
args. GetReturnValue (). Set (String:: NewFromUtf8 (
isolate, "world" ). ToLocalChecked ());
}
void Initialize (Local<Object> exports) {
NODE_SET_METHOD (exports, "hello" , Method);
}
NODE_MODULE (NODE_GYP_MODULE_NAME, Initialize)
} // namespace demo copy
All Node.js addons must export an initialization function following
the pattern:
void Initialize (Local<Object> exports) ;
NODE_MODULE (NODE_GYP_MODULE_NAME, Initialize) copy
There is no semi-colon after NODE_MODULE as it's not a function (see
node.h ).
The module_name must match the filename of the final binary (excluding
the .node suffix).
In the hello.cc example, then, the initialization function is Initialize
and the addon module name is addon .
When building addons with node-gyp , using the macro NODE_GYP_MODULE_NAME as
the first parameter of NODE_MODULE() will ensure that the name of the final
binary will be passed to NODE_MODULE() .
Addons defined with NODE_MODULE() can not be loaded in multiple contexts or
multiple threads at the same time.
Context-aware addons #
There are environments in which Node.js addons may need to be loaded multiple
times in multiple contexts. For example, the Electron runtime runs multiple
instances of Node.js in a single process. Each instance will have its own
require() cache, and thus each instance will need a native addon to behave
correctly when loaded via require() . This means that the addon
must support multiple initializations.
A context-aware addon can be constructed by using the macro
NODE_MODULE_INITIALIZER , which expands to the name of a function which Node.js
will expect to find when it loads an addon. An addon can thus be initialized as
in the following example:
using namespace v8;
extern "C" NODE_MODULE_EXPORT void
NODE_MODULE_INITIALIZER (Local<Object> exports,
Local<Value> module ,
Local<Context> context) {
/* Perform addon initialization steps here. */
} copy
Another option is to use the macro NODE_MODULE_INIT() , which will also
construct a context-aware addon. Unlike NODE_MODULE() , which is used to
construct an addon around a given addon initializer function,
NODE_MODULE_INIT() serves as the declaration of such an initializer to be
followed by a function body.
The following three variables may be used inside the function body following an
invocation of NODE_MODULE_INIT() :
* Local<Object> exports ,
* Local<Value> module , and
* Local<Context> context
The choice to build a context-aware addon carries with it the responsibility of
carefully managing global static data. Since the addon may be loaded multiple
times, potentially even from different threads, any global static data stored
in the addon must be properly protected, and must not contain any persistent
references to JavaScript objects. The reason for this is that JavaScript
objects are only valid in one context, and will likely cause a crash when
accessed from the wrong context or from a different thread than the one on which
they were created.
The context-aware addon can be structured to avoid global static data by
performing the following steps:
* Define a class which will hold per-addon-instance data and which has a static
member of the form
static void DeleteInstance ( void * data) {
// Cast `data` to an instance of the class and delete it.
} copy
* Heap-allocate an instance of this class in the addon initializer. This can be
accomplished using the new keyword.
* Call node::AddEnvironmentCleanupHook() , passing it the above-created
instance and a pointer to DeleteInstance() . This will ensure the instance is
deleted when the environment is torn down.
* Store the instance of the class in a v8::External , and
* Pass the v8::External to all methods exposed to JavaScript by passing it
to v8::FunctionTemplate::New() or v8::Function::New() which creates the
native-backed JavaScript functions. The third parameter of
v8::FunctionTemplate::New() or v8::Function::New() accepts the
v8::External and makes it available in the native callback using the
v8::FunctionCallbackInfo::Data() method.
This will ensure that the per-addon-instance data reaches each binding that can
be called from JavaScript. The per-addon-instance data must also be passed into
any asynchronous callbacks the addon may create.
The following example illustrates the implementation of a context-aware addon:
# include <node.h>
using namespace v8;
class AddonData {
public :
explicit AddonData (Isolate* isolate) :
call_count( 0 ) {
// Ensure this per-addon-instance data is deleted at environment cleanup.
node:: AddEnvironmentCleanupHook (isolate, DeleteInstance, this );
}
// Per-addon data.
int call_count;
static void DeleteInstance ( void * data) {
delete static_cast <AddonData*>(data);
}
};
static void Method ( const v8::FunctionCallbackInfo<v8::Value>& info) {
// Retrieve the per-addon-instance data.
AddonData* data =
reinterpret_cast <AddonData*>(info. Data (). As <External>()-> Value ());
data->call_count++;
info. GetReturnValue (). Set (( double )data->call_count);
}
// Initialize this addon to be context-aware.
NODE_MODULE_INIT ( /* exports, module, context */ ) {
Isolate* isolate = context-> GetIsolate ();
// Create a new instance of `AddonData` for this instance of the addon and
// tie its life cycle to that of the Node.js environment.
AddonData* data = new AddonData (isolate);
// Wrap the data in a `v8::External` so we can pass it to the method we
// expose.
Local<External> external = External:: New (isolate, data);
// Expose the method `Method` to JavaScript, and make sure it receives the
// per-addon-instance data we created above by passing `external` as the
// third parameter to the `FunctionTemplate` constructor.
exports-> Set (context,
String:: NewFromUtf8 (isolate, "method" ). ToLocalChecked (),
FunctionTemplate:: New (isolate, Method, external)
-> GetFunction (context). ToLocalChecked ()). FromJust ();
} copy
Worker support #
History
Version Changes
v14.8.0, v12.19.0
Cleanup hooks may now be asynchronous.
In order to be loaded from multiple Node.js environments,
such as a main thread and a Worker thread, an add-on needs to either:
* Be an Node-API addon, or
* Be declared as context-aware using NODE_MODULE_INIT() as described above
In order to support Worker threads, addons need to clean up any resources
they may have allocated when such a thread exists. This can be achieved through
the usage of the AddEnvironmentCleanupHook() function:
void AddEnvironmentCleanupHook (v8::Isolate* isolate,
void (*fun)( void * arg),
void * arg) ; copy
This function adds a hook that will run before a given Node.js instance shuts
down. If necessary, such hooks can be removed before they are run using
RemoveEnvironmentCleanupHook() , which has the same signature. Callbacks are
run in last-in first-out order.
If necessary, there is an additional pair of AddEnvironmentCleanupHook()
and RemoveEnvironmentCleanupHook() overloads, where the cleanup hook takes a
callback function. This can be used for shutting down asynchronous resources,
such as any libuv handles registered by the addon.
The following addon.cc uses AddEnvironmentCleanupHook :
// addon.cc
# include <node.h>
# include <assert.h>
# include <stdlib.h>
using node::AddEnvironmentCleanupHook;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
// Note: In a real-world application, do not rely on static/global data.
static char cookie[] = "yum yum" ;
static int cleanup_cb1_called = 0 ;
static int cleanup_cb2_called = 0 ;
static void cleanup_cb1 ( void * arg) {
Isolate* isolate = static_cast <Isolate*>(arg);
HandleScope scope (isolate) ;
Local<Object> obj = Object:: New (isolate);
assert (!obj. IsEmpty ()); // assert VM is still alive
assert (obj-> IsObject ());
cleanup_cb1_called++;
}
static void cleanup_cb2 ( void * arg) {
assert (arg == static_cast < void *>(cookie));
cleanup_cb2_called++;
}
static void sanity_check ( void *) {
assert (cleanup_cb1_called == 1 );
assert (cleanup_cb2_called == 1 );
}
// Initialize this addon to be context-aware.
NODE_MODULE_INIT ( /* exports, module, context */ ) {
Isolate* isolate = context-> GetIsolate ();
AddEnvironmentCleanupHook (isolate, sanity_check, nullptr );
AddEnvironmentCleanupHook (isolate, cleanup_cb2, cookie);
AddEnvironmentCleanupHook (isolate, cleanup_cb1, isolate);
} copy
Test in JavaScript by running:
// test.js
require ( './build/Release/addon' ); copy
Building #
Once the source code has been written, it must be compiled into the binary
addon.node file. To do so, create a file called binding.gyp in the
top-level of the project describing the build configuration of the module
using a JSON-like format. This file is used by node-gyp , a tool written
specifically to compile Node.js addons.
{
"targets" : [
{
"target_name" : "addon" ,
"sources" : [ "hello.cc" ]
}
]
} copy
A version of the node-gyp utility is bundled and distributed with
Node.js as part of npm . This version is not made directly available for
developers to use and is intended only to support the ability to use the
npm install command to compile and install addons. Developers who wish to
use node-gyp directly can install it using the command
npm install -g node-gyp . See the node-gyp installation instructions for
more information, including platform-specific requirements.
Once the binding.gyp file has been created, use node-gyp configure to
generate the appropriate project build files for the current platform. This
will generate either a Makefile (on Unix platforms) or a vcxproj file
(on Windows) in the build/ directory.
Next, invoke the node-gyp build command to generate the compiled addon.node
file. This will be put into the build/Release/ directory.
When using npm install to install a Node.js addon, npm uses its own bundled
version of node-gyp to perform this same set of actions, generating a
compiled version of the addon for the user's platform on demand.
Once built, the binary addon can be used from within Node.js by pointing
require() to the built addon.node module:
// hello.js
const addon = require ( './build/Release/addon' );
console . log (addon. hello ());
// Prints: 'world' copy
Because the exact path to the compiled addon binary can vary depending on how
it is compiled (i.e. sometimes it may be in ./build/Debug/ ), addons can use
the bindings package to load the compiled module.
While the bindings package implementation is more sophisticated in how it
locates addon modules, it is essentially using a try…catch pattern similar to:
try {
return require ( './build/Release/addon.node' );
} catch (err) {
return require ( './build/Debug/addon.node' );
} copy
Linking to libraries included with Node.js #
Node.js uses statically linked libraries such as V8, libuv, and OpenSSL. All
addons are required to link to V8 and may link to any of the other dependencies
as well. Typically, this is as simple as including the appropriate
#include <...> statements (e.g. #include <v8.h> ) and node-gyp will locate
the appropriate headers automatically. However, there are a few caveats to be
aware of:
*
When node-gyp runs, it will detect the specific release version of Node.js
and download either the full source tarball or just the headers. If the full
source is downloaded, addons will have complete access to the full set of
Node.js dependencies. However, if only the Node.js headers are downloaded,
then only the symbols exported by Node.js will be available.
*
node-gyp can be run using the --nodedir flag pointing at a local Node.js
source image. Using this option, the addon will have access to the full set of
dependencies.
Loading addons using require() #
The filename extension of the compiled addon binary is .node (as opposed
to .dll or .so ). The require() function is written to look for
files with the .node file extension and initialize those as dynamically-linked
libraries.
When calling require() , the .node extension can usually be
omitted and Node.js will still find and initialize the addon. One caveat,
however, is that Node.js will first attempt to locate and load modules or
JavaS
Links found on this page
- Node.js [direct]
- About this documentation [direct]
- Usage and example [direct]
- Assertion testing [direct]
- Asynchronous context tracking [direct]
- Async hooks [direct]
- Buffer [direct]
- C++ addons [direct]
- C/C++ addons with Node-API [direct]
- C++ embedder API [direct]
- Child processes [direct]
- Cluster [direct]
- Command-line options [direct]
- Console [direct]
- Corepack [direct]
- Crypto [direct]
- Debugger [direct]
- Deprecated APIs [direct]
- Diagnostics Channel [direct]
- DNS [direct]
- Domain [direct]
- Errors [direct]
- Events [direct]
- File system [direct]
- Globals [direct]
- HTTP [direct]
- HTTP/2 [direct]
- HTTPS [direct]
- Inspector [direct]
- Internationalization [direct]
- Modules: CommonJS modules [direct]
- Modules: ECMAScript modules [direct]
- Modules: node:module API [direct]
- Modules: Packages [direct]
- Net [direct]
- OS [direct]
- Path [direct]
- Performance hooks [direct]
- Permissions [direct]
- Process [direct]
- Punycode [direct]
- Query strings [direct]
- Readline [direct]
- REPL [direct]
- Report [direct]
- Single executable applications [direct]
- Stream [direct]
- String decoder [direct]
- Test runner [direct]
- Timers [direct]
- TLS/SSL [direct]
- Trace events [direct]
- TTY [direct]
- UDP/datagram [direct]
- URL [direct]
- Utilities [direct]
- V8 [direct]
- VM [direct]
- WASI [direct]
- Web Crypto API [direct]
- Web Streams API [direct]
- Worker threads [direct]
- Zlib [direct]
- Code repository and issue tracker [direct]
- Index [direct]
- 20.x LTS [direct]
- 19.x [direct]
- 18.x LTS [direct]
- 17.x [direct]
- 16.x [direct]
- 15.x [direct]
- 14.x [direct]
- 13.x [direct]
- 12.x [direct]
- 11.x [direct]
- 10.x [direct]
- 9.x [direct]
- 8.x [direct]
- 7.x [direct]
- 6.x [direct]