{ "type": "module", "source": "doc/api/addons.md", "introduced_in": "v0.10.0", "miscs": [ { "textRaw": "C++ Addons", "name": "C++ Addons", "introduced_in": "v0.10.0", "type": "misc", "desc": "

Node.js Addons are dynamically-linked shared objects, written in C++, that\ncan be loaded into Node.js using the require() function, and used\njust as if they were an ordinary Node.js module. They are used primarily to\nprovide an interface between JavaScript running in Node.js and C/C++ libraries.

\n

At the moment, the method for implementing Addons is rather complicated,\ninvolving knowledge of several components and APIs:

\n\n

All of the following examples are available for download and may\nbe used as the starting-point for an Addon.

", "miscs": [ { "textRaw": "Hello world", "name": "hello_world", "desc": "

This \"Hello world\" example is a simple Addon, written in C++, that is the\nequivalent of the following JavaScript code:

\n
module.exports.hello = () => 'world';\n
\n

First, create the file hello.cc:

\n
// hello.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid Method(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid Initialize(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"hello\", Method);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)\n\n}  // namespace demo\n
\n

Note that all Node.js Addons must export an initialization function following\nthe pattern:

\n
void Initialize(Local<Object> exports);\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)\n
\n

There is no semi-colon after NODE_MODULE as it's not a function (see\nnode.h).

\n

The module_name must match the filename of the final binary (excluding\nthe .node suffix).

\n

In the hello.cc example, then, the initialization function is Initialize\nand the addon module name is addon.

\n

When building addons with node-gyp, using the macro NODE_GYP_MODULE_NAME as\nthe first parameter of NODE_MODULE() will ensure that the name of the final\nbinary will be passed to NODE_MODULE().

", "modules": [ { "textRaw": "Context-aware addons", "name": "context-aware_addons", "desc": "

There are environments in which Node.js addons may need to be loaded multiple\ntimes in multiple contexts. For example, the Electron runtime runs multiple\ninstances of Node.js in a single process. Each instance will have its own\nrequire() cache, and thus each instance will need a native addon to behave\ncorrectly when loaded via require(). From the addon's perspective, this means\nthat it must support multiple initializations.

\n

A context-aware addon can be constructed by using the macro\nNODE_MODULE_INITIALIZER, which expands to the name of a function which Node.js\nwill expect to find when it loads an addon. An addon can thus be initialized as\nin the following example:

\n
using namespace v8;\n\nextern \"C\" NODE_MODULE_EXPORT void\nNODE_MODULE_INITIALIZER(Local<Object> exports,\n                        Local<Value> module,\n                        Local<Context> context) {\n  /* Perform addon initialization steps here. */\n}\n
\n

Another option is to use the macro NODE_MODULE_INIT(), which will also\nconstruct a context-aware addon. Unlike NODE_MODULE(), which is used to\nconstruct an addon around a given addon initializer function,\nNODE_MODULE_INIT() serves as the declaration of such an initializer to be\nfollowed by a function body.

\n

The following three variables may be used inside the function body following an\ninvocation of NODE_MODULE_INIT():

\n\n

The choice to build a context-aware addon carries with it the responsibility of\ncarefully managing global static data. Since the addon may be loaded multiple\ntimes, potentially even from different threads, any global static data stored\nin the addon must be properly protected, and must not contain any persistent\nreferences to JavaScript objects. The reason for this is that JavaScript\nobjects are only valid in one context, and will likely cause a crash when\naccessed from the wrong context or from a different thread than the one on which\nthey were created.

\n

The context-aware addon can be structured to avoid global static data by\nperforming the following steps:

\n\n

This will ensure that the per-addon-instance data reaches each binding that can\nbe called from JavaScript. The per-addon-instance data must also be passed into\nany asynchronous callbacks the addon may create.

\n

The following example illustrates the implementation of a context-aware addon:

\n
#include <node.h>\n\nusing namespace v8;\n\nclass AddonData {\n public:\n  AddonData(Isolate* isolate, Local<Object> exports):\n      call_count(0) {\n    // Link the existence of this object instance to the existence of exports.\n    exports_.Reset(isolate, exports);\n    exports_.SetWeak(this, DeleteMe, WeakCallbackType::kParameter);\n  }\n\n  ~AddonData() {\n    if (!exports_.IsEmpty()) {\n      // Reset the reference to avoid leaking data.\n      exports_.ClearWeak();\n      exports_.Reset();\n    }\n  }\n\n  // Per-addon data.\n  int call_count;\n\n private:\n  // Method to call when \"exports\" is about to be garbage-collected.\n  static void DeleteMe(const WeakCallbackInfo<AddonData>& info) {\n    delete info.GetParameter();\n  }\n\n  // Weak handle to the \"exports\" object. An instance of this class will be\n  // destroyed along with the exports object to which it is weakly bound.\n  v8::Persistent<v8::Object> exports_;\n};\n\nstatic void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {\n  // Retrieve the per-addon-instance data.\n  AddonData* data =\n      reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());\n  data->call_count++;\n  info.GetReturnValue().Set((double)data->call_count);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n  Isolate* isolate = context->GetIsolate();\n\n  // Create a new instance of AddonData for this instance of the addon.\n  AddonData* data = new AddonData(isolate, exports);\n  // Wrap the data in a v8::External so we can pass it to the method we expose.\n  Local<External> external = External::New(isolate, data);\n\n  // Expose the method \"Method\" to JavaScript, and make sure it receives the\n  // per-addon-instance data we created above by passing `external` as the\n  // third parameter to the FunctionTemplate constructor.\n  exports->Set(context,\n               String::NewFromUtf8(isolate, \"method\", NewStringType::kNormal)\n                  .ToLocalChecked(),\n               FunctionTemplate::New(isolate, Method, external)\n                  ->GetFunction(context).ToLocalChecked()).FromJust();\n}\n
", "type": "module", "displayName": "Context-aware addons" }, { "textRaw": "Building", "name": "building", "desc": "

Once the source code has been written, it must be compiled into the binary\naddon.node file. To do so, create a file called binding.gyp in the\ntop-level of the project describing the build configuration of the module\nusing a JSON-like format. This file is used by node-gyp — a tool written\nspecifically to compile Node.js Addons.

\n
{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"hello.cc\" ]\n    }\n  ]\n}\n
\n

A version of the node-gyp utility is bundled and distributed with\nNode.js as part of npm. This version is not made directly available for\ndevelopers to use and is intended only to support the ability to use the\nnpm install command to compile and install Addons. Developers who wish to\nuse node-gyp directly can install it using the command\nnpm install -g node-gyp. See the node-gyp installation instructions for\nmore information, including platform-specific requirements.

\n

Once the binding.gyp file has been created, use node-gyp configure to\ngenerate the appropriate project build files for the current platform. This\nwill generate either a Makefile (on Unix platforms) or a vcxproj file\n(on Windows) in the build/ directory.

\n

Next, invoke the node-gyp build command to generate the compiled addon.node\nfile. This will be put into the build/Release/ directory.

\n

When using npm install to install a Node.js Addon, npm uses its own bundled\nversion of node-gyp to perform this same set of actions, generating a\ncompiled version of the Addon for the user's platform on demand.

\n

Once built, the binary Addon can be used from within Node.js by pointing\nrequire() to the built addon.node module:

\n
// hello.js\nconst addon = require('./build/Release/addon');\n\nconsole.log(addon.hello());\n// Prints: 'world'\n
\n

Please see the examples below for further information or\nhttps://github.com/arturadib/node-qt for an example in production.

\n

Because the exact path to the compiled Addon binary can vary depending on how\nit is compiled (i.e. sometimes it may be in ./build/Debug/), Addons can use\nthe bindings package to load the compiled module.

\n

Note that while the bindings package implementation is more sophisticated\nin how it locates Addon modules, it is essentially using a try-catch pattern\nsimilar to:

\n
try {\n  return require('./build/Release/addon.node');\n} catch (err) {\n  return require('./build/Debug/addon.node');\n}\n
", "type": "module", "displayName": "Building" }, { "textRaw": "Linking to Node.js' own dependencies", "name": "linking_to_node.js'_own_dependencies", "desc": "

Node.js uses a number of statically linked libraries such as V8, libuv and\nOpenSSL. All Addons are required to link to V8 and may link to any of the\nother dependencies as well. Typically, this is as simple as including\nthe appropriate #include <...> statements (e.g. #include <v8.h>) and\nnode-gyp will locate the appropriate headers automatically. However, there\nare a few caveats to be aware of:

\n", "type": "module", "displayName": "Linking to Node.js' own dependencies" }, { "textRaw": "Loading Addons using require()", "name": "loading_addons_using_require()", "desc": "

The filename extension of the compiled Addon binary is .node (as opposed\nto .dll or .so). The require() function is written to look for\nfiles with the .node file extension and initialize those as dynamically-linked\nlibraries.

\n

When calling require(), the .node extension can usually be\nomitted and Node.js will still find and initialize the Addon. One caveat,\nhowever, is that Node.js will first attempt to locate and load modules or\nJavaScript files that happen to share the same base name. For instance, if\nthere is a file addon.js in the same directory as the binary addon.node,\nthen require('addon') will give precedence to the addon.js file\nand load it instead.

", "type": "module", "displayName": "Loading Addons using require()" } ], "type": "misc", "displayName": "Hello world" }, { "textRaw": "Native Abstractions for Node.js", "name": "native_abstractions_for_node.js", "desc": "

Each of the examples illustrated in this document make direct use of the\nNode.js and V8 APIs for implementing Addons. It is important to understand\nthat the V8 API can, and has, changed dramatically from one V8 release to the\nnext (and one major Node.js release to the next). With each change, Addons may\nneed to be updated and recompiled in order to continue functioning. The Node.js\nrelease schedule is designed to minimize the frequency and impact of such\nchanges but there is little that Node.js can do currently to ensure stability\nof the V8 APIs.

\n

The Native Abstractions for Node.js (or nan) provide a set of tools that\nAddon developers are recommended to use to keep compatibility between past and\nfuture releases of V8 and Node.js. See the nan examples for an\nillustration of how it can be used.

", "type": "misc", "displayName": "Native Abstractions for Node.js" }, { "textRaw": "N-API", "name": "n-api", "stability": 2, "stabilityText": "Stable", "desc": "

N-API is an API for building native Addons. It is independent from\nthe underlying JavaScript runtime (e.g. V8) and is maintained as part of\nNode.js itself. This API will be Application Binary Interface (ABI) stable\nacross versions of Node.js. It is intended to insulate Addons from\nchanges in the underlying JavaScript engine and allow modules\ncompiled for one version to run on later versions of Node.js without\nrecompilation. Addons are built/packaged with the same approach/tools\noutlined in this document (node-gyp, etc.). The only difference is the\nset of APIs that are used by the native code. Instead of using the V8\nor Native Abstractions for Node.js APIs, the functions available\nin the N-API are used.

\n

Creating and maintaining an addon that benefits from the ABI stability\nprovided by N-API carries with it certain\nimplementation considerations.

\n

To use N-API in the above \"Hello world\" example, replace the content of\nhello.cc with the following. All other instructions remain the same.

\n
// hello.cc using N-API\n#include <node_api.h>\n\nnamespace demo {\n\nnapi_value Method(napi_env env, napi_callback_info args) {\n  napi_value greeting;\n  napi_status status;\n\n  status = napi_create_string_utf8(env, \"world\", NAPI_AUTO_LENGTH, &greeting);\n  if (status != napi_ok) return nullptr;\n  return greeting;\n}\n\nnapi_value init(napi_env env, napi_value exports) {\n  napi_status status;\n  napi_value fn;\n\n  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);\n  if (status != napi_ok) return nullptr;\n\n  status = napi_set_named_property(env, exports, \"hello\", fn);\n  if (status != napi_ok) return nullptr;\n  return exports;\n}\n\nNAPI_MODULE(NODE_GYP_MODULE_NAME, init)\n\n}  // namespace demo\n
\n

The functions available and how to use them are documented in the\nsection titled C/C++ Addons - N-API.

", "type": "misc", "displayName": "N-API" }, { "textRaw": "Addon examples", "name": "addon_examples", "desc": "

Following are some example Addons intended to help developers get started. The\nexamples make use of the V8 APIs. Refer to the online V8 reference\nfor help with the various V8 calls, and V8's Embedder's Guide for an\nexplanation of several concepts used such as handles, scopes, function\ntemplates, etc.

\n

Each of these examples using the following binding.gyp file:

\n
{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"addon.cc\" ]\n    }\n  ]\n}\n
\n

In cases where there is more than one .cc file, simply add the additional\nfilename to the sources array:

\n
\"sources\": [\"addon.cc\", \"myexample.cc\"]\n
\n

Once the binding.gyp file is ready, the example Addons can be configured and\nbuilt using node-gyp:

\n
$ node-gyp configure build\n
", "modules": [ { "textRaw": "Function arguments", "name": "function_arguments", "desc": "

Addons will typically expose objects and functions that can be accessed from\nJavaScript running within Node.js. When functions are invoked from JavaScript,\nthe input arguments and return value must be mapped to and from the C/C++\ncode.

\n

The following example illustrates how to read function arguments passed from\nJavaScript and how to return a result:

\n
// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Exception;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// This is the implementation of the \"add\" method\n// Input arguments are passed using the\n// const FunctionCallbackInfo<Value>& args struct\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  // Check the number of arguments passed.\n  if (args.Length() < 2) {\n    // Throw an Error that is passed back to JavaScript\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong number of arguments\",\n                            NewStringType::kNormal).ToLocalChecked()));\n    return;\n  }\n\n  // Check the argument types\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong arguments\",\n                            NewStringType::kNormal).ToLocalChecked()));\n    return;\n  }\n\n  // Perform the operation\n  double value =\n      args[0].As<Number>()->Value() + args[1].As<Number>()->Value();\n  Local<Number> num = Number::New(isolate, value);\n\n  // Set the return value (using the passed in\n  // FunctionCallbackInfo<Value>&)\n  args.GetReturnValue().Set(num);\n}\n\nvoid Init(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
\n

Once compiled, the example Addon can be required and used from within Node.js:

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nconsole.log('This should be eight:', addon.add(3, 5));\n
", "type": "module", "displayName": "Function arguments" }, { "textRaw": "Callbacks", "name": "callbacks", "desc": "

It is common practice within Addons to pass JavaScript functions to a C++\nfunction and execute them from there. The following example illustrates how\nto invoke such callbacks:

\n
// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Null;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid RunCallback(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = {\n      String::NewFromUtf8(isolate,\n                          \"hello world\",\n                          NewStringType::kNormal).ToLocalChecked() };\n  cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", RunCallback);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
\n

Note that this example uses a two-argument form of Init() that receives\nthe full module object as the second argument. This allows the Addon\nto completely overwrite exports with a single function instead of\nadding the function as a property of exports.

\n

To test it, run the following JavaScript:

\n
// test.js\nconst addon = require('./build/Release/addon');\n\naddon((msg) => {\n  console.log(msg);\n// Prints: 'hello world'\n});\n
\n

Note that, in this example, the callback function is invoked synchronously.

", "type": "module", "displayName": "Callbacks" }, { "textRaw": "Object factory", "name": "object_factory", "desc": "

Addons can create and return new objects from within a C++ function as\nillustrated in the following example. An object is created and returned with a\nproperty msg that echoes the string passed to createObject():

\n
// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  Local<Object> obj = Object::New(isolate);\n  obj->Set(context,\n           String::NewFromUtf8(isolate,\n                               \"msg\",\n                               NewStringType::kNormal).ToLocalChecked(),\n                               args[0]->ToString(context).ToLocalChecked())\n           .FromJust();\n\n  args.GetReturnValue().Set(obj);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
\n

To test it in JavaScript:

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon('hello');\nconst obj2 = addon('world');\nconsole.log(obj1.msg, obj2.msg);\n// Prints: 'hello world'\n
", "type": "module", "displayName": "Object factory" }, { "textRaw": "Function factory", "name": "function_factory", "desc": "

Another common scenario is creating JavaScript functions that wrap C++\nfunctions and returning those back to JavaScript:

\n
// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid MyFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"hello world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid CreateFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);\n  Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();\n\n  // omit this to make it anonymous\n  fn->SetName(String::NewFromUtf8(\n      isolate, \"theFunction\", NewStringType::kNormal).ToLocalChecked());\n\n  args.GetReturnValue().Set(fn);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateFunction);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
\n

To test:

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nconst fn = addon();\nconsole.log(fn());\n// Prints: 'hello world'\n
", "type": "module", "displayName": "Function factory" }, { "textRaw": "Wrapping C++ objects", "name": "wrapping_c++_objects", "desc": "

It is also possible to wrap C++ objects/classes in a way that allows new\ninstances to be created using the JavaScript new operator:

\n
// addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Local;\nusing v8::Object;\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init(exports);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
\n

Then, in myobject.h, the wrapper class inherits from node::ObjectWrap:

\n
// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Local<v8::Object> exports);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n
\n

In myobject.cc, implement the various methods that are to be exposed.\nBelow, the method plusOne() is exposed by adding it to the constructor's\nprototype:

\n
// myobject.cc\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Number;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Local<Object> exports) {\n  Isolate* isolate = exports->GetIsolate();\n\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n  exports->Set(context, String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked(),\n               tpl->GetFunction(context).ToLocalChecked()).FromJust();\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> result =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(result);\n  }\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n
\n

To build this example, the myobject.cc file must be added to the\nbinding.gyp:

\n
{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n
\n

Test it with:

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj = new addon.MyObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n
\n

The destructor for a wrapper object will run when the object is\ngarbage-collected. For destructor testing, there are command-line flags that\ncan be used to make it possible to force garbage collection. These flags are\nprovided by the underlying V8 JavaScript engine. They are subject to change\nor removal at any time. They are not documented by Node.js or V8, and they\nshould never be used outside of testing.

", "type": "module", "displayName": "Wrapping C++ objects" }, { "textRaw": "Factory of wrapped objects", "name": "factory_of_wrapped_objects", "desc": "

Alternatively, it is possible to use a factory pattern to avoid explicitly\ncreating object instances using the JavaScript new operator:

\n
const obj = addon.createObject();\n// instead of:\n// const obj = new addon.Object();\n
\n

First, the createObject() method is implemented in addon.cc:

\n
// addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid InitAll(Local<Object> exports, Local<Object> module) {\n  MyObject::Init(exports->GetIsolate());\n\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
\n

In myobject.h, the static method NewInstance() is added to handle\ninstantiating the object. This method takes the place of using new in\nJavaScript:

\n
// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Isolate* isolate);\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n
\n

The implementation in myobject.cc is similar to the previous example:

\n
// myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Number;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Isolate* isolate) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n
\n

Once again, to build this example, the myobject.cc file must be added to the\nbinding.gyp:

\n
{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n
\n

Test it with:

\n
// test.js\nconst createObject = require('./build/Release/addon');\n\nconst obj = createObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n\nconst obj2 = createObject(20);\nconsole.log(obj2.plusOne());\n// Prints: 21\nconsole.log(obj2.plusOne());\n// Prints: 22\nconsole.log(obj2.plusOne());\n// Prints: 23\n
", "type": "module", "displayName": "Factory of wrapped objects" }, { "textRaw": "Passing wrapped objects around", "name": "passing_wrapped_objects_around", "desc": "

In addition to wrapping and returning C++ objects, it is possible to pass\nwrapped objects around by unwrapping them with the Node.js helper function\nnode::ObjectWrap::Unwrap. The following examples shows a function add()\nthat can take two MyObject objects as input arguments:

\n
// addon.cc\n#include <node.h>\n#include <node_object_wrap.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject(context).ToLocalChecked());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject(context).ToLocalChecked());\n\n  double sum = obj1->value() + obj2->value();\n  args.GetReturnValue().Set(Number::New(isolate, sum));\n}\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init(exports->GetIsolate());\n\n  NODE_SET_METHOD(exports, \"createObject\", CreateObject);\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
\n

In myobject.h, a new public method is added to allow access to private values\nafter unwrapping the object.

\n
// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Isolate* isolate);\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n  inline double value() const { return value_; }\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n
\n

The implementation of myobject.cc is similar to before:

\n
// myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Isolate* isolate) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\n}  // namespace demo\n
\n

Test it with:

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon.createObject(10);\nconst obj2 = addon.createObject(20);\nconst result = addon.add(obj1, obj2);\n\nconsole.log(result);\n// Prints: 30\n
", "type": "module", "displayName": "Passing wrapped objects around" }, { "textRaw": "AtExit hooks", "name": "atexit_hooks", "desc": "

An AtExit hook is a function that is invoked after the Node.js event loop\nhas ended but before the JavaScript VM is terminated and Node.js shuts down.\nAtExit hooks are registered using the node::AtExit API.

", "modules": [ { "textRaw": "void AtExit(callback, args)", "name": "void_atexit(callback,_args)", "desc": "\n

Registers exit hooks that run after the event loop has ended but before the VM\nis killed.

\n

AtExit takes two parameters: a pointer to a callback function to run at exit,\nand a pointer to untyped context data to be passed to that callback.

\n

Callbacks are run in last-in first-out order.

\n

The following addon.cc implements AtExit:

\n
// addon.cc\n#include <assert.h>\n#include <stdlib.h>\n#include <node.h>\n\nnamespace demo {\n\nusing node::AtExit;\nusing v8::HandleScope;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\n\nstatic char cookie[] = \"yum yum\";\nstatic int at_exit_cb1_called = 0;\nstatic int at_exit_cb2_called = 0;\n\nstatic void at_exit_cb1(void* arg) {\n  Isolate* isolate = static_cast<Isolate*>(arg);\n  HandleScope scope(isolate);\n  Local<Object> obj = Object::New(isolate);\n  assert(!obj.IsEmpty());  // assert VM is still alive\n  assert(obj->IsObject());\n  at_exit_cb1_called++;\n}\n\nstatic void at_exit_cb2(void* arg) {\n  assert(arg == static_cast<void*>(cookie));\n  at_exit_cb2_called++;\n}\n\nstatic void sanity_check(void*) {\n  assert(at_exit_cb1_called == 1);\n  assert(at_exit_cb2_called == 2);\n}\n\nvoid init(Local<Object> exports) {\n  AtExit(at_exit_cb2, cookie);\n  AtExit(at_exit_cb2, cookie);\n  AtExit(at_exit_cb1, exports->GetIsolate());\n  AtExit(sanity_check);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, init)\n\n}  // namespace demo\n
\n

Test in JavaScript by running:

\n
// test.js\nrequire('./build/Release/addon');\n
", "type": "module", "displayName": "void AtExit(callback, args)" } ], "type": "module", "displayName": "AtExit hooks" } ], "type": "misc", "displayName": "Addon examples" } ] } ] }