Open In App

Why do we need C++ Addons in Node.js ?

In this article, we will see why do we need C++ Addons in NodeJS.

Why do we need C++ Addons?



Pre-requisites:

Module Installation: Install the required module using the following command.



npm i -g  node-gyp

 

Folder Structure: It will look like this.

Now create binding.gyp, calculate.cc file with the following code.

Filename: binding.gyp

{
  "targets": [
      {
          "target_name": "calculate", // Name of C++ Addons.
          "sources": [ "calculate.cc" ] // Source of C++ file.
      }
  ]
}




#include <node.h>
#include <iostream>
  
namespace calculate {
     using v8:: FunctionCallbackInfo;
     using v8 :: Isolate;
     using v8 :: Local;
     using v8 :: Object;
     using v8 :: Number;
     using v8 :: Value;
  
     // C++ add function.
     void Sum(const FunctionCallbackInfo<Value>&args)
     {
         Isolate* isolate = args.GetIsolate();
         int i;
         double x = 3.141526, y = 2.718;
         for(i=0; i<1000000000; i++)
         {
             x += y;
         }
  
         auto total = Number::New(isolate,x);
         args.GetReturnValue().Set(total);
     }
  
     // Exports our method
     void Initialize(Local<Object> exports) {
         NODE_SET_METHOD(exports, "calc", Sum);
     }
  
     NODE_MODULE(NODE_GYP_MODULE_NAME,Initialize);
 }




// Require addons
const calculate = require('./build/Release/calculate');
  
// Javascript add function.
function calc() {
  
    // Two variables.
    let i, x = 3.141526, y = 2.718;
    for (i = 0; i < 1000000000; i++) {
        x += y;
  
    }
    let total = x;
    return total;
}
  
console.time('c++');
calculate.calc();
console.timeEnd('c++');
  
console.time('js');
calc();
  
console.timeEnd('js');

Step to run the application: To build and configure, run the following command.

node-gyp configure build 
node app.js

Output:

c++: 1.184s
js: 1.207s

Article Tags :