Skip to content

Node.js native C modules

Graham Wakefield edited this page Jun 20, 2019 · 25 revisions

Writing Node.js modules in C/C++ ("native modules")

Overview:

  • make project folder as a git repo
  • as a Node.js module, it is defined in a package.json file
  • write C++ code against the Node.js API
  • build it with node-gyp via definitions in a binding.gyp file
  • test it / wrap it with a index.js file

N-API, AKA Node.js C API, "napi" or "node_api.h"

The API reference docs are here -- but they are really a reference, and not a good place to learn from initially.

There is an official repository of examples here

Here's a quick tutorial on the napi API

Why use N-API?

There are several different APIs for developing native (i.e. C/C++) Node.js modules. Until recently, the recommended API was called nan, however this C++ API does not guarantee stability. But nowadays it is recommended instead to use the napi API, which does guarantee ABI stability. There is also a C++ wrapper of this API, with the confusingly-similar name of node-addon-api.

Starting a new module project:

Assuming a module called "addon":

mkdir addon
cd addon
git init
npm init

Binding.gyp

https://gyp.gsrc.io/docs/InputFormatReference.md

Clone this wiki locally