Node-API Headers

1.8.0 · active · verified Sun Apr 19

The `node-api-headers` package provides the essential C/C++ header files required for building Node.js native add-ons using the Node-API (formerly N-API). These headers enable developers to create native modules that benefit from ABI stability across different Node.js versions, simplifying maintenance and ensuring forward compatibility. The package, currently at version 1.8.0, maintains a frequent release cadence, often monthly or bi-monthly, specifically tracking and incorporating updates from the Node.js core repository. This package is crucial for build tools like `node-gyp` and `CMake.js`, which rely on these headers to compile native C/C++ code into `.node` files runnable within Node.js applications. It differentiates itself by being the official source for these headers, abstracting away the need to download full Node.js source distributions for native module development.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic Node.js native add-on using Node-API headers. It includes a C++ source file (`myaddon.cc`), a `binding.gyp` file for `node-gyp` to compile the add-on, and a JavaScript file (`index.js`) to load and use the compiled native module. The `binding.gyp` file dynamically fetches the header path from the `node-api-headers` package.

/* file: myaddon.cc */
#include <node_api.h>

napi_value Method(napi_env env, napi_callback_info info) {
  napi_value greeting;
  napi_status status;

  status = napi_create_string_utf8(env, "Hello from Node-API C++ addon!", NAPI_AUTO_LENGTH, &greeting);
  if (status != napi_ok) return nullptr;
  return greeting;
}

napi_value Init(napi_env env, napi_value exports) {
  napi_status status;
  napi_property_descriptor desc = {
    "hello", 0, Method, 0, 0, 0, napi_default, 0
  };
  status = napi_define_properties(env, exports, 1, &desc);
  if (status != napi_ok) return nullptr;
  return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)

/* file: binding.gyp */
{
  "targets": [
    {
      "target_name": "myaddon",
      "sources": [ "myaddon.cc" ],
      "include_dirs": [
        "<!@(node -p \"require('node-api-headers').include_dir\")"
      ]
    }
  ]
}

/* file: index.js */
const addon = require('bindings')('myaddon');
console.log(addon.hello());

view raw JSON →