Convert Figma logo to code with AI

nodejs logonode-addon-api

Module for using Node-API from C++

2,284
481
2,284
14

Top Related Projects

Node.js C++ addon examples from http://nodejs.org/docs/latest/api/addons.html

3,322

Native Abstractions for Node.js

6,610

A framework for building compiled Node.js add-ons in Rust via Node-API

10,190

Node.js native addon build tool

Quick Overview

Node-addon-api is a C++ wrapper for Node.js' N-API, providing a higher-level abstraction for building native addons. It simplifies the process of creating native modules for Node.js, allowing developers to write C++ code that integrates seamlessly with JavaScript.

Pros

  • Easier to use than raw N-API, with a more intuitive C++ interface
  • Provides better type safety and error handling
  • Compatible across different Node.js versions
  • Reduces the need for manual memory management

Cons

  • May have a slight performance overhead compared to raw N-API
  • Learning curve for developers not familiar with C++ or native addon development
  • Limited documentation and examples compared to more established libraries

Code Examples

  1. Creating a simple function:
#include <napi.h>

Napi::Value Add(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  
  if (info.Length() < 2) {
    Napi::TypeError::New(env, "Wrong number of arguments").ThrowAsJavaScriptException();
    return env.Null();
  }
  
  double arg0 = info[0].As<Napi::Number>().DoubleValue();
  double arg1 = info[1].As<Napi::Number>().DoubleValue();
  
  Napi::Number num = Napi::Number::New(env, arg0 + arg1);
  
  return num;
}
  1. Wrapping a C++ class:
#include <napi.h>

class MyClass : public Napi::ObjectWrap<MyClass> {
public:
  static Napi::Object Init(Napi::Env env, Napi::Object exports);
  MyClass(const Napi::CallbackInfo& info);

private:
  Napi::Value GetValue(const Napi::CallbackInfo& info);
  Napi::Value SetValue(const Napi::CallbackInfo& info);
  
  double value_;
};

Napi::Object MyClass::Init(Napi::Env env, Napi::Object exports) {
  Napi::Function func = DefineClass(env, "MyClass", {
    InstanceMethod("getValue", &MyClass::GetValue),
    InstanceMethod("setValue", &MyClass::SetValue)
  });
  
  exports.Set("MyClass", func);
  return exports;
}

MyClass::MyClass(const Napi::CallbackInfo& info) : Napi::ObjectWrap<MyClass>(info) {
  value_ = 0.0;
}

Napi::Value MyClass::GetValue(const Napi::CallbackInfo& info) {
  return Napi::Number::New(info.Env(), value_);
}

Napi::Value MyClass::SetValue(const Napi::CallbackInfo& info) {
  value_ = info[0].As<Napi::Number>().DoubleValue();
  return Napi::Number::New(info.Env(), value_);
}
  1. Asynchronous operations:
#include <napi.h>

class AsyncWorker : public Napi::AsyncWorker {
public:
  AsyncWorker(Napi::Function& callback)
    : Napi::AsyncWorker(callback) {}

  void Execute() override {
    // Perform time-consuming operation
  }

  void OnOK() override {
    Napi::HandleScope scope(Env());
    Callback().Call({Env().Null(), Napi::String::New(Env(), "Operation completed")});
  }
};

Napi::Value DoAsyncWork(const Napi::CallbackInfo& info) {
  Napi::Function callback = info[0].As<Napi::Function>();
  AsyncWorker* worker = new AsyncWorker(callback);
  worker->Queue();
  return info.Env().Undefined();
}

Getting Started

  1. Install node-addon-api:

Competitor Comparisons

Node.js C++ addon examples from http://nodejs.org/docs/latest/api/addons.html

Pros of node-addon-examples

  • Provides a wide range of practical examples for different use cases
  • Demonstrates various techniques and best practices for Node.js addon development
  • Includes examples for both N-API and node-addon-api

Cons of node-addon-examples

  • Not a comprehensive library or framework for addon development
  • May require more setup and understanding to implement in real-world projects
  • Examples might not cover all possible scenarios or edge cases

Code Comparison

node-addon-examples:

#include <napi.h>

Napi::String Method(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  return Napi::String::New(env, "world");
}

node-addon-api:

#include <napi.h>

Napi::Value Method(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  return Napi::String::New(env, "world");
}

The code snippets are very similar, as node-addon-examples often uses node-addon-api. The main difference is that node-addon-examples provides context and explanations around the code, while node-addon-api focuses on the API implementation itself.

3,322

Native Abstractions for Node.js

Pros of nan

  • More mature and established, with a longer history of use in Node.js addons
  • Wider community support and extensive documentation
  • Compatible with older Node.js versions

Cons of nan

  • Requires more boilerplate code
  • Less type-safe compared to node-addon-api
  • May become deprecated in the future as Node-API gains more adoption

Code Comparison

nan:

NAN_METHOD(Example) {
  v8::Local<v8::String> result = Nan::New("Hello").ToLocalChecked();
  info.GetReturnValue().Set(result);
}

node-addon-api:

Napi::Value Example(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  return Napi::String::New(env, "Hello");
}

Summary

nan is a more established solution for creating Node.js native addons, offering broader compatibility and community support. However, node-addon-api provides a more modern, type-safe approach with less boilerplate code. node-addon-api is built on top of Node-API, which is the future direction for native addons in Node.js.

While nan still has its place in legacy projects and for supporting older Node.js versions, new projects are encouraged to use node-addon-api for better long-term maintainability and performance.

6,610

A framework for building compiled Node.js add-ons in Rust via Node-API

Pros of napi-rs

  • Written in Rust, offering memory safety and performance benefits
  • Supports async operations natively
  • Provides a more ergonomic API for Rust developers

Cons of napi-rs

  • Requires knowledge of Rust, which may have a steeper learning curve
  • Smaller community and ecosystem compared to node-addon-api
  • Less mature and potentially less stable than node-addon-api

Code Comparison

node-addon-api (C++):

Napi::Object Init(Napi::Env env, Napi::Object exports) {
  exports.Set("hello", Napi::Function::New(env, Hello));
  return exports;
}

NODE_API_MODULE(addon, Init)

napi-rs (Rust):

#[napi]
fn hello(name: String) -> String {
  format!("Hello, {}!", name)
}

#[napi]
pub fn init(exports: JsObject) -> Result<()> {
  exports.create_named_method("hello", hello)?;
  Ok(())
}

Both node-addon-api and napi-rs aim to simplify the process of creating native addons for Node.js. node-addon-api is more established and uses C++, while napi-rs leverages Rust's safety features and provides a more idiomatic experience for Rust developers. The choice between the two depends on the developer's language preference, project requirements, and familiarity with the respective ecosystems.

10,190

Node.js native addon build tool

Pros of node-gyp

  • More established and widely used in the Node.js ecosystem
  • Supports a broader range of C/C++ projects and build systems
  • Better compatibility with older Node.js versions

Cons of node-gyp

  • Steeper learning curve for developers new to native addons
  • Requires Python and C++ build tools, which can be challenging to set up
  • More verbose and complex configuration files

Code Comparison

node-gyp (binding.gyp):

{
  "targets": [{
    "target_name": "addon",
    "sources": [ "addon.cc" ],
    "include_dirs": ["<!(node -e \"require('nan')\")"]
  }]
}

node-addon-api (addon.cc):

#include <napi.h>

Napi::Object Init(Napi::Env env, Napi::Object exports) {
  // Add function exports here
  return exports;
}

NODE_API_MODULE(addon, Init)

node-gyp is a build system for compiling native addon modules for Node.js. It's more flexible but requires more setup. node-addon-api, on the other hand, provides a C++ wrapper for the N-API, offering an easier way to create native addons with better ABI stability. node-addon-api is simpler to use and doesn't require Python, but it may not be suitable for all types of native addons or older Node.js versions.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

node-addon-api module

codecov

NPM NPM

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

API References

API references are available in the doc directory.

Current version: 8.4.0

(See CHANGELOG.md for complete Changelog)

node-addon-api is based on Node-API and supports using different Node-API versions. This allows addons built with it to run with Node.js versions which support the targeted Node-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 18.x.

Badges

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

Node-API v1 Badge Node-API v2 Badge Node-API v3 Badge Node-API v4 Badge Node-API v5 Badge Node-API v6 Badge Node-API v7 Badge Node-API v8 Badge Node-API v9 Badge Node-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
Jack XiaJckXia
Kevin EadyKevinEady
Michael Dawsonmhdawson
Nicola Del GobboNickNaso
Vladimir Morozovvmoroz
Emeritus

Emeritus

NameGitHub Link
Arunesh Chandraaruneshchandra
Benjamin Byholmkkoopa
Gabriel Schulhofgabrielschulhof
Hitesh Kanwathirthadigitalinfinity
Jason Ginchereaujasongin
Jim Schlightjschlight
Sampson Gaosampsongao
Taylor Wollboingoing

License

Licensed under MIT

NPM DownloadsLast 30 Days