Category Archives: Uncategorized

Let’s start with C++ NodeJS addon

First things first – I know literally nothing about NodeJS C++ addons. I have an experience with C++ and with interopearation between C+++ and other languages, but not JavaScript and definitely not NodeJS (except small, top-secret project in bozon).

So we are going to learn together ;] Happy?

Let’s get started with getting project structure prepared – current architecture divides the project into (at least) three layers, which makes it kind of “Buissness Logic Desing Pattern”:

  • JavaScript / HTML presentation layer.
  • JS / NodeJS thin proxy as a business logic.
  • C++ addon for NodeJS for whole OBD2 protocol and connection.

The first layer has to run on desktop – which does not often happen for JS apps. That’s where Electron kicks in. It is a framework for building desktop apps with NodeJS, HTML and CSS, which nicely fits my needs.

Sometimes I am actually a lazy person and don’t like to create whole project structure by hand, so for that I’ve been using Bozon. It is not perfect, but creates a project scaffolding with build script, run script and unit testing script (created with Gulp, whatever this is). Exactly what I need, everything else I can do myself. You can see it created yourself in this commit.

Okay, enought about libraries, let’s start with creating NodeJS addon in C++, so we can see how it works.

First we create a source code of our binding layer file as described in documentation:

Then we have to create a binding.gyp describing build configuration:

At the end install and run the node-gyp:

Now we have a scaffolding for the C++ plugin which can be easily built. There is one more thing actuall, I don’t like writing C++ in the notepad, so I wanted to have an XCode project and this is quite easy to do with one command:

Clever. The build does not work without node-gyp configure ran after though.

Then we want nan module which creates an abstraction between v8 and node version and our C++ code. I wanted to do this myself, but there is no need to reinvent the wheel:

And change our bindings file, there should be added information about include directories:

Now every use of #include <node.h>  should be replaced with #inlcude <nan.h> .

Also if you use like me Xcode you need to edit project “binding.xcodeproj” and add to search paths nan directory:

Also we will in the future have more than one NodeJS library so we might want some common code – path to headers should be added the same way.

This is all for now, in next post we are going to try this with bluetooth enumeration on macOS and think about why node-gyp does not create proper project with HEADER_SEARCH_PATHS.