C++ addons (N-API)

This article is created only to show you the C++ addons feature because maybe you didn’t know them. I will publish a more in deep article about this, so don’t worry about it.

C++ addons

Node.js Addons are dynamically-linked shared objects, written in C++, that can be loaded into Node.js using the require() function, and used just as if they were an ordinary Node.js module. They are used primarily to provide an interface between JavaScript running in Node.js and C/C++ libraries.

1
2
# npm i -g node-gyp // global
$ npm i bindings // local

Configuration file

Create this configuration file to tell node-gyp what to do:

1
2
3
4
5
6
7
8
9
10
11
{
"targets": [
{
"target_name": "addon",
"sources": [ "hello.cc" ],
"include_dirs": [
"<!(node -e \"require('nan')\")"
]
}
]
}

C++ code

We are going to export a function which can add two numbers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <nan.h>

void Add(const Nan::FunctionCallbackInfo<v8::Value>& info) {

if (info.Length() < 2) {
Nan::ThrowTypeError("Wrong number of arguments");
return;
}

if (!info[0]->IsNumber() || !info[1]->IsNumber()) {
Nan::ThrowTypeError("Wrong arguments");
return;
}

double arg0 = info[0]->NumberValue();
double arg1 = info[1]->NumberValue();
v8::Local<v8::Number> num = Nan::New(arg0 + arg1);

info.GetReturnValue().Set(num);
}

void Init(v8::Local<v8::Object> exports) {
exports->Set(Nan::New("add").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(Add)->GetFunction());
}

NODE_MODULE(addon, Init)

Build

Execute the following comand to configure + build at the same time:

1
$ node-gyp rebuild

Simple Node.js script

We are going to use the C++ addon that we have just created:

1
2
3
const { add } = require('bindings')('addon.node')

console.log(`add(30,50) should be eighty: ${add(30, 50)}`)
1
2
$ node test.js
// add(30,50) should be eighty: 80

As you can see, this could be strange at first time, but the possibilities are infinite. Give your Node.js projects the C++ power.

References