How to Integrate C++ With Nodejs?

By Prajwal Haniya

Techletter #45 | September 27, 2023

The v8 engine is written in C++. So, the JavaScript community will embrace C++. We can write addons using C++ and improve application performance. So, in this tech letter let’s explore how we can write an addon using C++ and integrate it with nodejs.

Create a cpp file addon.cpp

#include <node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void Method(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(
      isolate, "This message is coming from the cpp module").ToLocalChecked());
}

void Initialize(Local<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

}

Create a binding.gyp file in the same directory as above file. And in that file add the following code:

{
  "targets": [
    {
      "target_name": "addon",
      "sources": ["addon.cpp"]
    }
  ]
}

Create a build of cpp file using node-gyp. You need to install node-gyp first using command npm install -g node-gyp. Then create the build using the command node-gyp configure build

Now create a nodejs file app.js

const addon = require('./build/Release/addon');

console.log(addon.hello());

Now, you can run the above file using the command node app.js. You should get the output This message is coming from the cpp module.

This letter was short. I do have a lot of questions like how this works, how internally it communicates, what exactly the build contains, what is gyp file, etc. I will write about all of them in the upcoming articles. This was just a simple letter, where I could document my today’s learning. Hope this added a little value to you. If it did, don't forget to subscribe to techletters.