Socket
Socket
Sign inDemoInstall

node-addon-api

Package Overview
Dependencies
0
Maintainers
5
Versions
45
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

node-addon-api


Version published
Maintainers
5
Install size
677 kB
Created

Package description

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

Changelog

Source

2020-12-17 Version 3.1.0, @NickNaso

Notable changes:

API
  • Added Napi::TypedThreadSafeFunction class that is a new implementation for thread-safe functions.
  • Fixed leak on Napi::AsyncProgressWorkerBase.
  • Fixed empty data on Napi::AsyncProgressWorker::OnProgress caused by race conditions of Napi::AsyncProgressWorker.
  • Added Napi::ArrayBuffer::Detach() and Napi::ArrayBuffer::IsDetached().
  • Fixed problem on Napi::FinalizeCallback it needs to create a Napi::HandleScope when it calls Napi::ObjectWrap::~ObjectWrap().
Documentation
  • Added documentation for Napi::TypedThreadSafeFunction.
  • Removed unsued Doxygen file.
  • Clarified when to use N-API.
  • Added support information.
  • Some minor corrections all over the documentation.
TEST
  • Added test for Napi::TypedThreadSafeFunction.
  • Fixed testing for specific N-API version.
  • Some minor corrections all over the test suite.

TOOL

  • Setup github actions for tests.
  • Added stale action.
  • Removed sudo tag from Travis CI.
  • Added clang-format.
  • Added pre-commit package for linting.

Commits

  • [ff642c5b85] - doc: fix tsfn docs to reflect true implementation (#860) (Kevin Eady)
  • [86feeebf54] - src: empty data OnProgress in AsyncProgressWorker (legendecas) #853
  • [a7fb5fb31c] - action: add stale action (#856) (Michael Dawson)
  • [fd44609885] - chore: setup github actions for tests (#854) (legendecas) #854
  • [c52ace4813] - script: fix complains that js files are not supported on npm run lint:fix (#852) (legendecas)
  • [b4a3364ad5] - doc: remove unused Doxygen file (#851) (Michael Dawson)
  • [b810466ae2] - doc: clarify when to use N-API (#849) (Michael Dawson)
  • [528b9f6832] - test: remove sudo from travis (#850) (Michael Dawson)
  • [4bb680de4e] - Remove misleading sentence (#847) (Nikolai Vavilov) #847
  • [48e6b584a3] - Merge pull request #742 from KevinEady/contexted-tsfn-api-gcc-4 (Gabriel Schulhof)
  • [d5e37210cc] - tools: print more instructions on clang-format check failed (#846) (legendecas) #846
  • [d9e11ff2c9] - doc: add support info (#843) (Michael Dawson) #843
  • [356e93d69a] - test: fixup testing for specific N-API version (#840) (Michael Dawson) #840
  • [5e5b9ce1b7] - Apply formatting changes (Kevin Eady)
  • [559ad8c0c0] - Merge remote-tracking branch 'upstream/master' into contexted-tsfn-api-gcc-4 (Kevin Eady)
  • [c24c455ced] - Rename to TypedThreadSafeFunction (Kevin Eady)
  • [63b43f4125] - test: fix buildType bug objectwrap_worker_thread (raisinten) #837
  • [6321f2ba1a] - test: fix typos in addon_build/index.js (raisinten) #838
  • [59c6a6aeb0] - fix: git-clang-format doesn't recognize no changes requested on given files (#835) (legendecas)
  • [1427b3ef78] - src: create a HandleScope in FinalizeCallback (blagoev) #832
  • [8fb5820557] - build: add incremental clang-format checks (legendecas) #819
  • [2c02d317e5] - build: add pre-commit package for linting (#823) (Kevin Eady)
  • [1b52c28eb8] - Clean up AsyncProgressWorker documentation (#831) (mastergberry)
  • [4abe7cfe30] - test: rename tsfnex test files (Kevin Eady)
  • [c9563caa25] - src: add ArrayBuffer::Detach() and ::IsDetached() (Tobias Nießen) #659
  • [c79cabaed2] - doc: avoid directing users to HTTP (#828) (Tobias Nießen)
  • [7a13f861ab] - doc: fix additional typo (Kevin Eady)
  • [7ec9741dd2] - Merge remote-tracking branch 'upstream/master' into contexted-tsfn-api-gcc-4 (Kevin Eady)
  • [f5fad239fa] - Update object_reference.md (#827) (kidneysolo)
  • [35b65712c2] - Fix: some typos in documentation (#826) (Helio Frota)
  • [8983383000] - Fix: some typos in the document (#825) (Ziqiu Zhao)
  • [826e466ef6] - Fixed example in addon.md. (#820) (nempoBu4) #820
  • [b54f5eb788] - Additional changes from review (Kevin Eady)
  • [59f27dac9a] - Fix common.gypi (Kevin Eady)
  • [151a914c99] - Apply documentation suggestions from code review (Kevin Eady)
  • [ceb27d4949] - src: fix leak in AsyncProgressWorkerBase<DataType> (Ferdinand Holzer) #795

Readme

Source

node-addon-api module

This module contains header-only C++ wrapper classes which simplify the use of the C based N-API provided by Node.js when using C++. It provides a C++ object model and exception handling semantics with low overhead.

There are three options for implementing addons: N-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 N-API as outlined in C/C++ addons in Node.js core, use N-API. Refer to C/C++ addons with N-API for more information on N-API.

N-API is an ABI stable C interface provided by Node.js for building native addons. It is independent from the underlying JavaScript runtime (e.g. V8 or ChakraCore) and is maintained as part of Node.js itself. It is intended to insulate native addons from changes in the underlying JavaScript engine and allow modules compiled for one version to run on later versions of Node.js without recompilation.

The node-addon-api module, which is not part of Node.js, preserves the benefits of the N-API as it consists only of inline code that depends only on the stable API provided by N-API. As such, modules built against one version of Node.js using node-addon-api should run without having to be rebuilt with newer versions of Node.js.

It is important to remember that other Node.js interfaces such as libuv (included in a project via #include <uv.h>) are not ABI-stable across Node.js major versions. Thus, an addon must use N-API and/or node-addon-api exclusively and build against a version of Node.js that includes an implementation of N-API (meaning an active LTS version of Node.js) in order to benefit from ABI stability across Node.js major versions. Node.js provides an ABI stability guide containing a detailed explanation of ABI stability in general, and the N-API ABI stability guarantee in particular.

As new APIs are added to N-API, node-addon-api must be updated to provide wrappers for those new APIs. For this reason node-addon-api provides methods that allow callers to obtain the underlying N-API handles so direct calls to N-API and the use of the objects/methods provided by node-addon-api can be used together. For example, in order to be able to use an API for which the node-addon-api does not yet provide a wrapper.

APIs exposed by node-addon-api are generally used to create and manipulate JavaScript values. Concepts and operations generally map to ideas specified in the ECMA262 Language Specification.

The N-API Resource offers an excellent orientation and tips for developers just getting started with N-API and node-addon-api.

Current version: 3.1.0

(See CHANGELOG.md for complete Changelog)

NPM NPM

node-addon-api is based on N-API and supports using different N-API versions. This allows addons built with it to run with Node.js versions which support the targeted N-API version. However the node-addon-api support model is to support only the active LTS Node.js versions. This means that every year there will be a new major which drops support for the Node.js LTS version which has gone out of service.

The oldest Node.js version supported by the current version of node-addon-api is Node.js 10.x.

Setup

API Documentation

The following is the documentation for node-addon-api.

Examples

Are you new to node-addon-api? Take a look at our examples

Tests

To run the node-addon-api tests do:

npm install
npm test

To avoid testing the deprecated portions of the API run

npm install
npm test --disable-deprecated

To run the tests targetting a specific version of N-API run

npm install
export NAPI_VERSION=X
npm test --NAPI_VERSION=X

where X is the version of N-API you want to target.

Debug

To run the node-addon-api tests with --debug option:

npm run-script dev

If you want faster build, you might use the following option:

npm run-script dev:incremental

Take a look and get inspired by our test suite

Benchmarks

You can run the available benchmarks using the following command:

npm run-script benchmark

See benchmark/README.md for more details about running and adding benchmarks.

More resource and info about native Addons

As node-addon-api's core mission is to expose the plain C N-API as C++ wrappers, tools that facilitate n-api/node-addon-api providing more convenient patterns on developing a Node.js add-ons with n-api/node-addon-api can be published to NPM as standalone packages. It is also recommended to tag such packages with node-addon-api to provide more visibility to the community.

Quick links to NPM searches: keywords:node-addon-api.

Badges

The use of badges is recommended to indicate the minimum version of N-API required for the module. This helps to determine which Node.js major versions are supported. Addon maintainers can consult the N-API support matrix to determine which Node.js versions provide a given N-API version. The following badges are available:

N-API v1 Badge N-API v2 Badge N-API v3 Badge N-API v4 Badge N-API v5 Badge N-API v6 Badge N-API Experimental Version Badge

Contributing

We love contributions from the community to node-addon-api! See CONTRIBUTING.md for more details on our philosophy around extending this module.

Team members

Active

NameGitHub Link
Anna Henningsenaddaleax
Chengzhong Wulegendecas
Gabriel Schulhofgabrielschulhof
Hitesh Kanwathirthadigitalinfinity
Jim Schlightjschlight
Michael Dawsonmhdawson
Kevin EadyKevinEady
Nicola Del GobboNickNaso

Emeritus

NameGitHub Link
Arunesh Chandraaruneshchandra
Benjamin Byholmkkoopa
Jason Ginchereaujasongin
Sampson Gaosampsongao
Taylor Wollboingoing

Licensed under MIT

Keywords

FAQs

Last updated on 17 Dec 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc