N-API Macros

2.2.2 · active · verified Sun Apr 19

napi-macros is a lightweight, header-only C/C++ library providing a set of utility macros designed to simplify the development of Node.js N-API modules. It aims to reduce boilerplate code commonly associated with N-API, particularly for argument parsing, return value handling, and function/constant exports. As of April 2026, the current stable version is 2.2.2. This package is maintained by mafintosh, a prominent figure in the Node.js ecosystem, and typically sees updates in response to N-API specification changes or user contributions, rather than a fixed release cadence. Its key differentiator is its direct, macro-based approach, offering a minimal abstraction layer over the raw N-API C functions, making it suitable for developers who prefer fine-grained control and low-level C/C++ integration compared to higher-level C++ wrappers like `node-addon-api` or Rust-based solutions such as `napi-rs`.

Common errors

Warnings

Install

Imports

Quickstart

This C++ snippet demonstrates a basic N-API module using `napi-macros`. It defines a `times_two` method that takes a single integer argument from JavaScript, multiplies it by two, and returns the result. It showcases `NAPI_METHOD`, argument parsing (`NAPI_ARGV`, `NAPI_ARGV_INT32`), returning values (`NAPI_RETURN_INT32`), and module initialization/export (`NAPI_INIT`, `NAPI_EXPORT_FUNCTION`).

#include <node_api.h>
#include <napi-macros.h>

NAPI_METHOD(times_two) {
  // Expects 1 argument
  NAPI_ARGV(1)
  // Get the first argument as an int32, named 'number'
  NAPI_ARGV_INT32(number, 0)

  // Perform operation
  number *= 2;

  // Return the result as an int32
  NAPI_RETURN_INT32(number)
}

NAPI_INIT() {
  // Export the 'times_two' function to JavaScript
  NAPI_EXPORT_FUNCTION(times_two)
}

view raw JSON →