Node-Addon-API C++ Wrapper for Node.js Native Addons

8.7.0 · active · verified Sun Apr 19

Node-Addon-API (N-API) is a C++ wrapper library that significantly simplifies the development of Node.js native add-ons. It provides a higher-level, more idiomatic C++ interface over the raw C-based Node-API, leveraging modern C++ features like RAII (Resource Acquisition Is Initialization) and exceptions for safer and more robust native module development. This abstraction layer helps manage memory and resources automatically, reducing common errors associated with manual memory management in C. The current stable version is 8.7.0, with minor feature and bugfix releases occurring every few months. Its primary differentiator is making Node.js native module development accessible to C++ developers by providing familiar C++ paradigms, while maintaining ABI stability across Node.js major versions, ensuring compiled add-ons continue to work without recompilation against newer Node.js releases. It is the recommended path for new native addon development.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates building a simple 'hello world' native addon in C++ using Node-Addon-API and loading/executing it from a Node.js JavaScript application. Includes the `binding.gyp` configuration.

/* C++ source file: hello.cc */
#include <napi.h>

// Simple synchronous method that returns a string
Napi::String Method(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  return Napi::String::New(env, "world");
}

// Initialize the addon
Napi::Object Init(Napi::Env env, Napi::Object exports) {
  exports.Set(Napi::String::New(env, "hello"),
              Napi::Function::New(env, Method));
  return exports;
}

// Register the addon module
NODE_API_MODULE(hello, Init)

/* binding.gyp (build configuration for node-gyp) */
{
  "targets": [
    {
      "target_name": "hello",
      "sources": [ "hello.cc" ],
      "include_dirs": [
        "<!@(node -p \"require('node-addon-api').include\")"
      ],
      "cflags!": [ "-fno-exceptions" ],
      "cflags_cc!": [ "-fno-exceptions" ],
      "defines": [ "NAPI_CPP_EXCEPTIONS" ],
      "libraries": []
    }
  ]
}

/* JavaScript usage: index.js */
// To build the addon: run `node-gyp rebuild` in your terminal.
// This will create a `build/Release/hello.node` file.

const addon = require('./build/Release/hello.node');

console.log('addon.hello() =', addon.hello()); // Expected output: addon.hello() = world

view raw JSON →