What is node-addon-api?
The node-addon-api package is a helper library for building Node.js Addons in C++. It provides a C++ API that abstracts away the complexities of working with the low-level V8 and N-API provided by Node.js, making it easier to develop native addons.
What are node-addon-api's main functionalities?
Object Wrapping
Object wrapping allows C++ classes to be represented as JavaScript objects. It provides an easy way to create and manage objects that have a one-to-one relationship with C++ objects.
Napi::ObjectReference MyClass::constructor;
MyClass::MyClass(const Napi::CallbackInfo& info) : Napi::ObjectWrap<MyClass>(info) {
// constructor implementation
}
Napi::Object MyClass::Init(Napi::Env env, Napi::Object exports) {
Napi::HandleScope scope(env);
Napi::Function func = DefineClass(env, "MyClass", {
InstanceMethod("myMethod", &MyClass::MyMethod)
});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("MyClass", func);
return exports;
}
Function Arguments
The package provides a way to handle function arguments passed from JavaScript to C++ with type checking and conversion utilities.
Napi::Value MyFunction(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 2) {
Napi::TypeError::New(env, "Expected at least two arguments").ThrowAsJavaScriptException();
}
Napi::String arg0 = info[0].As<Napi::String>();
double arg1 = info[1].As<Napi::Number>().DoubleValue();
// function implementation
return Napi::String::New(env, "result");
}
Asynchronous Operations
node-addon-api provides utilities for performing asynchronous operations, allowing long-running tasks to be executed without blocking the Node.js event loop.
class MyAsyncWorker : public Napi::AsyncWorker {
public:
MyAsyncWorker(Napi::Function& callback) : AsyncWorker(callback) {}
void Execute() override {
// Do work in another thread
}
void OnOK() override {
Napi::HandleScope scope(Env());
Callback().Call({Env().Null(), Napi::String::New(Env(), "Success")});
}
};
Napi::Value RunAsyncWork(const Napi::CallbackInfo& info) {
Napi::Function callback = info[0].As<Napi::Function>();
MyAsyncWorker* worker = new MyAsyncWorker(callback);
worker->Queue();
return info.Env().Undefined();
}
Other packages similar to node-addon-api
nan
The 'nan' package is a header file filled with macros and utilities for making addon development for different versions of V8 easier. It predates N-API and node-addon-api, and while it's still used, node-addon-api is recommended for most cases due to its simpler API and direct support for N-API.
ffi-napi
The 'ffi-napi' package allows for calling foreign functions of dynamic libraries from Node.js. It is similar to node-addon-api in that it allows for native functionality in Node.js, but it focuses on interfacing with existing libraries rather than writing new native modules.
neon
The 'neon' package is a Rust framework for writing safe and fast native Node.js modules. Like node-addon-api, it simplifies the process of writing native addons but does so using Rust instead of C++.
Node.js API (N-API) Package
This package contains header-only C++ wrapper classes for the ABI-stable
Node.js API (N-API), along with library code that enables
backward-compatibility with use with older versions of Node.js that do
not have N-API built-in.
API Documentation
Getting Started
To use N-API in a native module:
- Add a dependency on this package to
package.json
:
"dependencies": {
"node-addon-api": "0.3.3",
}
- Reference this package's include directory and gyp file in
binding.gyp
:
'include_dirs': ["<!@(node -p \"require('node-addon-api').include\")"],
'dependencies': ["<!(node -p \"require('node-addon-api').gyp\")"],
- Decide whether the package will enable C++ exceptions in the N-API wrapper.
The base ABI-stable C APIs do not throw or handle C++ exceptions, but the
N-API C++ wrapper classes may optionally
integrate C++ and JavaScript exception-handling
.
To enable that capability, C++ exceptions must be enabled in
binding.gyp
:
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'CLANG_CXX_LIBRARY': 'libc++',
'MACOSX_DEPLOYMENT_TARGET': '10.7',
},
'msvs_settings': {
'VCCLCompilerTool': { 'ExceptionHandling': 1 },
},
Alternatively, disable use of C++ exceptions in N-API:
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
- Include
napi.h
in the native module code.
To ensure only ABI-stable APIs are used, DO NOT include
node.h
, nan.h
, or v8.h
.
#include "napi.h"
At build time, the N-API back-compat library code will be used only when the
targeted node version does not have N-API built-in.
Conversion Tool
To make the migration to node-addon-api easier, we have provided a script to help
complete the steps listed above. To use the conversion script:
- Go to your module directory
cd [module_path]
- Install node-addon-api module
npm install node-addon-api
- Run node-addon-api conversion script
node ./node_modules/node-addon-api/tools/conversion.js ./
- While this script makes conversion easier, it still cannot fully convert
the module. The next step is to try to build the module and complete the
remaining conversions necessary to allow it to compile and pass all of the
module's tests.
WG Members / Collaborators