Native Abstractions for Node.js (NAN)

2.26.2 · active · verified Sun Apr 19

nan (Native Abstractions for Node.js) is a crucial C++ header-only library designed to provide a consistent compatibility layer for developing Node.js native add-ons. It expertly abstracts away the frequent and significant breaking changes introduced by updates to the V8 JavaScript engine and Node.js core APIs. This allows add-on developers to write C++ code that compiles and functions reliably across a broad spectrum of Node.js versions, spanning from legacy 0.8 releases up to the current Node.js 25. The current stable version is 2.26.2. Releases are generally aligned with new major Node.js LTS lines or critical V8 API shifts. Its primary differentiator is offering a stable C++ API surface, thereby eliminating the complex, version-specific conditional compilation macros developers would otherwise need to manage manually. Importantly, nan does not expose any direct JavaScript runtime APIs; its sole focus is on simplifying the development and maintenance of native modules.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic Node.js native add-on using `nan`, including the `package.json`, `binding.gyp`, C++ source, and a simple JavaScript entry point. Run `npm install` and then `node index.js`.

/* package.json */
{
  "name": "nan-example-addon",
  "version": "1.0.0",
  "private": true,
  "gypfile": true,
  "dependencies": {
    "nan": "^2.26.2"
  },
  "scripts": {
    "install": "node-gyp rebuild"
  }
}

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

/* src/addon.cc */
#include <nan.h>

void Method(const Nan::FunctionCallbackInfo<v8::Value>& info) {
  info.GetReturnValue().Set(Nan::New("world").ToLocalChecked());
}

void Initialize(v8::Local<v8::Object> exports) {
  Nan::SetMethod(exports, "hello", Method);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

/* index.js */
const addon = require('./build/Release/myaddon.node');
console.log(addon.hello()); // Outputs: world

view raw JSON →